Random UTF-8 characters

Home

14 Jun 2016 in reactjavascriptredux

React: Containers and Components

At work we've been using React heavily on one of our new projects. Like most projects we are using redux to load data from the server. In doing so testing becomes a bit more difficult. In order to make our components more testable we are using containers.

You might have heard of containers before, they are also called 'Higher Order Components'. Theses are components that wrap other components. They isolate the redux logic outside of the component doing the rendering. This makes testing the components that render your views much simpler.

Lets look at a practical example. Let's say you have a view that component a video's details. We'll break this into two parts. The container that loads the video from the server and the component that renders the data.

First off we use react router to nest our views. Our router configuration would look like this.

This nests the component within the container. This ensures the container is called, it also also for simple reuse if you have other view that load the same object. Here is an example if you also had an edit view that need to load a video.

Now lets look at a container. A container loads the object via an action. It connects that object to its children via props.

As you can see on componentWillMount an action is dispatched to load the video. I'm ignoring what happens in action creators, middleware and stores for this demo. If you do want to learn more about that, I suggest reading the redux docs. The container passes the video to the props of all its children.

This leaves you to only do the rendering in the component.

The component does not need to know about loading objects or redux. It's purely for rendering. This makes testing simpler as well as giving you proper separation of concerns.