Creating Higher-Order Component
Explore how to create a Higher-Order Component (HOC) in React that encapsulates state and event handler logic. This lesson guides you through building a reusable HOC called HasIndex, which manages an index state with increment and decrement functions. You will understand how to write tests to drive development and ensure functionality, improving component reusability and maintainability.
We'll cover the following...
Creating reusable higher-order component
At the bottom of this lesson, we have the test-driven-carousel project from the previous chapter, take a look at the Carousel component. In addition to rendering a somewhat complex DOM tree, it also has one piece of state and two event handlers that manipulate that state. Let’s try building an HOC that encapsulates that logic.
-
Well-implemented HOCs tend to be highly reusable, and this one will be no exception. It’ll manage the state for any component with an “index” prop, meaning a number that can go from 0 up to some limit. Call it
HasIndex. Start with a ...