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.