Separating container components from presentational components is a popular React programming pattern. It is a special application of the concepts learned in the Stateless Components From Stateful Components module.
If a component has to have state, make calculations based on props, or manage any other complex logic, then that component shouldn’t also have to render HTML-like JSX.
The functional part of a component (state, calculations, etc.) can be separated into a container component.
GuineaPigs.js contains a lot of logic! It has to select the correct guinea pig to render, wait for the right amount of time before rendering, render an image, select the next correct guinea pig, and so on.
Let’s separate the logic from the
GuineaPigs component into a container component.
Near the top left of the code editor, click on the folder icon. Create a new folder named containers. containers/ should be next to components/.
Inside of containers/, create a new file named GuineaPigsContainer.js. Make sure that GuineaPigs is plural, but Container is singular!
Once you have made containers/GuineaPigsContainer.js, click Run.
You want to separate the logic of this component class into a container component. How do you do that?
To start, just make a copy. After that, you can delete the appropriate parts.
Highlight the entire contents of components/GuineaPigs.js, and copy it to the clipboard.
Now, open containers/GuineaPigsContainer.js.
Click inside the empty file, and paste. containers/GuineaPigsContainer.js and components/GuineaPigs.js should be identical.