In this short post, I would like to describe how to structure react components.

The main idea is to have a structure that helps to build highly maintainable and scalable software and makes it easy for developers to navigate and find files.

Each component has its own directory and inside it, we put all related files. This gives us self-contained component which is easy to understand and test. It will be also relatively easy to move components around or to create a separate package since all important code will be already packed up.

Example components

We have to start with components directory which contains “global” components, used in different parts of an application.

Above we can see <Search /> component, which is used in <TopNavbar /> and somewhere else in the app, that’s why both components are at the same main level.

TopNavbar/ directory contains following files and directories:

index.js - it contains only single line which exports TopNavbar default. This makes it nice and easy to import component.

export { default } from './TopNavbar';

TopNavbar.jsx - main component structure (layout).

- main component structure (layout). TopNavbar.stories.js - isolated stories for react-storybook.

- isolated stories for react-storybook. TopNavbar.test.js - our beloved tests.

- our beloved tests. components/ - private components. They can be only used by its parent or siblings.

- private components. They can be only used by its parent or siblings. styled-components/ - when you are using styled-components or glamorous it’s useful to keep them separated. Those components should have no markup and should contain only styling. Those are also private components.

TopNavbar has only one private component, DropdownMenu . Private components contain own tests, other private components, and styled-components.

Stories for react-storybook are only created for the main component not for private ones.

Conclusion

At first, this structure may look complex and overcomplicated. But it is worth the price. I believe this pattern will keep growing application clean and tidy and will help with building maintainable code.

Also, it gives a lot of flexibility for future changes. When some component has to be reused, you can just move its directory to the top level and change import path in one place.

Please comment below, I will appreciate any feedback.