Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic components with higher order components

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.

like image 866
Daaavvy Avatar asked Jun 11 '18 05:06

Daaavvy


People also ask

What are higher-order components example?

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.

What are higher-order components?

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.

Do higher-order components work with functional components?

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.

What are pure components and higher-order components?

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.


1 Answers

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!

like image 154
Archie Avatar answered Sep 18 '22 15:09

Archie