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

1
import React, { useState } from 'react'
2
3
interface VisibilityProps {
4
isVisible?: boolean
5
}
6
7
/**
8
* HOC that adds an `isVisible` prop that stops a component from rendering if
9
* `isVisible===false`
10
* @param WrappedComponent component to be selectively hidden
11
* @returns null if `isVisible` is false
12
*/
13
export function withVisibility<P>(WrappedComponent: React.ComponentType<P>) {
14
const VisibityControlled = (props: P & VisibilityProps) => {
15
if (props.isVisible === false) {
16
return null
17
}
18
19
return <WrappedComponent {...props} />
20
}
21
22
return VisibityControlled
23
}