Web & iOS dev – Ruby, Rails, RubyMotion & React

Paul Sturgess

How to Write and Test a Stateless React Component

Recently I’ve been learning Redux state container for React apps and it actively encourages ‘stateless’ components. This blog post will describe how these can be written and tested.

Note that you can write stateless components whether you’re using Redux or not!

What is a stateless component?

Redux introduces the concept of ‘presentational’ and ‘container’ components and the major difference between the two is that your presentational components should not be aware of Redux.

Without getting into the details of exactly how Redux works, the consequence of this separation of responsibilities means your presentational components can be fairly simple.

Certainly if they don’t make use of any React lifecycle methods (like componentDidUpdate) they can start life as a simple function that just returns the required output.

What does a stateless component look like?

Below is an example taken from a Todo app, what it does isn’t important. The key thing to notice is that it’s just a function that returns a list item.

Three props are defined onClick, completed and text. There’s no state manipulation.

So how is stateless component tested?

When using ReactTestUtils.renderIntoDocument it will not work with a stateless component – you’ll get an error ‘instance must be a composite component’.

The way around this is to use a component created by extending React.Component to wrap the stateless component. You’ll see in the test below a Wrapper component is created.

Once you’ve done that you can reach into the component to grab out specific DOM elements or other components.