Joshua Comeau digs into how styled-components works by re-building the basics. A fun and useful journey.
styled-components seems like the biggest player in the CSS-in-React market. Despite being in that world, I haven’t yet been fully compelled by it. I’m a big fan of the basics: scoped styles by way of unique class names. I also like that it works with hot module reloading as it all happens in JavaScript. But I get those through css-modules, and I like the file-separation and Sass support I get through css-modules. There are a few things I’m starting to come around on though (a little):
- Even with css-modules, you still have to think of names. Even if it’s just like
.root
or whatever. With styled-components you attach the styles right to the component and don’t really name anything. - With css-modules, you’re applying the styles directly to an HTML element only. With styled-components you can apply the styles to custom components and it will slap the styles on by way of spreading props later.
- Because the styles are literally in the JavaScript files, you get JavaScript stuff you can use—ternaries, prop access, fancy math, etc.
Styled Components are great! As you get deeper into it you slowly learn more and more great stuff you can do with it! It really is my favorite kind of styling in React!
Shipping only the CSS needed for the components in view is another huge advantage.
Not sure if the naming cognitive load changes much with styled components. Still have to name each component.
Didn’t we spend a decade, about a decade ago, teaching people how style attributes to HTML tags are bad?