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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.