Functional Higher Order Components (HOCs) with Typescript
Updated: 03 September 2023
An HOC in React is a component that wraps another component to provide additional props or functionality to the wrapped component
Here’s a simple example of how we can create an HOC using Typescript:
The component below will provide an isVisible
prop to a component which will alolow us to show or hide it selectively
1import React, { useState } from 'react'2
3interface VisibilityProps {4 isVisible?: boolean5}6
7/**8 * HOC that adds an `isVisible` prop that stops a component from rendering if9 * `isVisible===false`10 * @param WrappedComponent component to be selectively hidden11 * @returns null if `isVisible` is false12 */13export function withVisibility<P>(WrappedComponent: React.ComponentType<P>) {14 const VisibityControlled = (props: P & VisibilityProps) => {15 if (props.isVisible === false) {16 return null17 }18
19 return <WrappedComponent {...props} />20 }21
22 return VisibityControlled23}