Testing Stateful Components

Both of the React components we’ve built so far are stateless: their render output is determined entirely by the props they receive, allowing us to express them as a single function. This has the advantage of simplicity. But a carousel is stateful: it needs to keep track of which slide it’s currently showing. In this section, we’ll take a TDD approach to building a Carousel component with internal state.

Start with a stub implementation of the component. Since functional components can’t have state, make it a subclass of React.PureComponent:

 // src/Carousel.js
 import​ React ​from​ ​'react'​;
 
 class​ Carousel ​extends​ React.PureComponent {
  render() {
 return​ <div />;
  }
 }
 
 export​ ​default​ Carousel; ...

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.