Making Higher-Order Components

In the abstract, a higher-order component is defined as any function that takes a component and returns another component. Typically, the component returned by the HOC function is a wrapper around the original component that adds functionality. Here’s a simple example:

const​ BindProps = (Component, boundProps) => {
 const​ ComponentWithBoundProps = props => (
<Component ​{​...props​}​ ​{​...boundProps​}​ />
  );
  ComponentWithBoundProps.displayName =
`BindProps(​${Component.displayName || Component.name}​)`​;
 return​ ComponentWithBoundProps;
 };
 
const​ CarouselWithTestAttr = BindProps(Carousel, {
 'data-test-id'​: ​'carousel'​,
 });

The BindProps HOC takes two arguments, a component ...

Get Test-Driven React now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.