Styled-components organization

Gemmi picture Gemmi · Mar 23, 2017 · Viewed 17.3k times · Source

I want to use styled-components in my app and I am wondering how to organize it.

Basically styled-components are assigned to specific component for reusability.

But what about styled-components which I would like to use many times in other components (for example animations components)? Should I create a file where I will keep these 'global' styled-components and import it to many components?

Is it good practice?

Answer

mxstbr picture mxstbr · Mar 24, 2017

This is what most of my big production applications built with styled-components look like:

src
├── App
│   ├── Header
│   │   ├── Logo.js    
│   │   ├── Title.js   
│   │   ├── Subtitle.js
│   │   └── index.js
│   └── Footer
│       ├── List.js
│       ├── ListItem.js
│       ├── Wrapper.js
│       └── index.js
├── shared
│   ├── Button.js
│   ├── Card.js
│   ├── InfiniteList.js
│   ├── EmojiPicker
│   └── Icons
└── index.js

The App folder contains all the specific components that make up your bigger application. (you might structure that by route in your real app) Each of those bigger components is a folder with an index.js file and a bunch of styled components in individual files.

While I'm building my application and I notice I need a styled component from one bigger component in another bigger component, I drag its file to the shared/ folder, update all the imports and that's it! Over time shared/ becomes an improptu pattern library with all of the components I want/need to reuse throughout my entire app.

Another way that's fairly common is to have style.js files in the component folders which contains all of the styled components of that component. The upside being that you have less files that get in your way, but with the downside that it's harder to notice duplication and moving components into the shared folder is more work.

I personally use the first version more often than not, but that's probably just a matter of taste—try them both and see which one you like more!