React Higher-Order Component Patterns in TypeScript

  • An example might be a HOC which enforces that styles are set for a component via the style prop, a simple example of this being the following withBlueBackground HOC, which we’ll use throughout this article, and, as the name suggests, ensures the background colour is blue for the wrapped component:Note:…
  • : React.CSSProperties; name: string;}The type variable P is then used to specify the props for the unwrapped component to be passed into the HOC:UnwrappedComponent: is just an alias for React.StatelessComponentP | React.ComponentP, which would allow either a stateless functional component or a class component to be passed into the HOC.Object.assign()…
  • You will also face this same issue if you want to destructure the props using object rest:In terms of usage, the HOC can then be used as if it were a plain JavaScript HOC, with the added bonus that the wrapped component is statically typed:Pattern #2: Adding PropsSome HOCs add props…
  • : React.CSSProperties; name: string;}This will be more useful when additional props are injected, and ones which aren’t standard React props such as style.As for the HOC’s own props (WithBlueBackgroundProps) these are combined with the wrapped component’s props using a type intersection operator () :class WithBlueBackground extends React.Component P WithBlueBackgroundProps { …}This…
  • To demonstrate this with the withBlueBackground HOC, we will change it to require a component passed in that accepts a backgroundColor prop rather than setting the colour via style:Given we changed HelloProps to extend InjectedBlueBackgroundProps in pattern #2, no changes will need to be made to it, but the Hello…

Higher-order components (HOCs) in React are a powerful tool for code reuse between components. However, a common complaint of developers using TypeScript is that they are difficult to set types for…
Continue reading “React Higher-Order Component Patterns in TypeScript”