DEV Community

Discussion on: Let's Take a Look at CSS in JS with React in 2019 - Styled Components

Collapse
 
dyland profile image
Dylan Davenport

This may be a noob question (because I’m a React noob 😅) but why are styled components preferred over importing a CSS style sheet? I feel like that would keep our component files cleaner by not having so much extra code for the styles.

Collapse
 
adrianhelvik profile image
Adrian

For regular CSS: You get rid of global styles.

Say you write a component somewhere that uses the className 'container'. Then you can't use it in any other component style sheet without getting a conflict.

With CSS modules that is not a problem. The selling point against CSS modules is that you get more power. It lets you conditionally apply styles and build styles based on props.

Collapse
 
phizzard profile image
Phil Tietjen • Edited

Hey Dylan,

Ultimately I think it comes down to what the application needs from how big it may be, how many developers are contributing, etc. However, if it's less or cleaner code we're worried about there are a number of things to consider down the road with CSS vs Styled Components.

If you're just importing one CSS stylesheet, then off the bat in our JS we technically have less code for our styling because all we have is our import './style.css' line and the rest are className="some-class". Although, there may come a time where we might need to modify styles based on state or props in our react component which can lead us down to potentially adding logic to our components to adjust for this. In larger projects can lead to some messy components.

I think what might be a better way to think about styled-components over CSS is that it aims to align itself better with Reacts component-based architecture with scoping styles but also giving you an API that is intended to work well with Reacts component API and patterns, ideally, resulting in a cleaner codebase for your components and your styling.

My first entry in the series may be more helpful for a "Why not use CSS?" question, as I go more into CSS vs CSS in JS for React!

I hope it answers your question and thanks for asking it! :D

Collapse
 
dyland profile image
Dylan Davenport

Yes that helps immensely! I’ve done one React project so far and it wasn’t huge so as you said depending on the project size I was able to safely use a stylesheet without issue. I can totally see how that can become a problem as projects become more complex though.