I'd like to give my React component props a generic type but this is being lost when I wrap it in a higher order component (material-ui) how do I pass along the required information?
type Props<T> = {
data: Array<T>;
}
class MyComponent<T> extends React.Component<Props<T>> {
const StyledComponent = withStyles(styles)(MyComponent)
Using <StyledComponent<myType
gives an error as it doesn't know about the generic.
Higher-Order Components are not part of the React API. They are the pattern that emerges from React's compositional nature. The component transforms props into UI, and a higher-order component converts a component into another component. The examples of HOCs are Redux's connect and Relay's createContainer.
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.
Higher-Order Components enable us to apply functional programming principles on components by embracing composition. React Hooks, in contrast, transformed pure (in the sense of functional programming) function components to stateful/side-effect burdened beasts.
Higher order components are JavaScript functions used for adding additional functionalities to the existing component. These functions are pure, which means they are receiving data and returning values according to that data. If the data changes, higher order functions are re-run with different data input.
My bet is to annotate your new component like this:
const StyledComponent: <T>(props: OuterProps<T>) => JSX.Element = withStyles(styles)(MyComponent) ;
Mind you probably need to differentiate OuterProps
and InnerProps
, see below example I made for reference:
https://stackblitz.com/edit/hoc-generics
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With