TL;DR: In this article, we will be looking at some of the various benefits of styled-components and why you should consider adopting it as your preferred CSS-in-JS framework.
What is styled-components?
I know the subject of CSS-in-JS is heavily debated in the frontend community especially among react developers so I’d ask that you keep an open mind.
Styling React components
There are many ways to style a react component:
- Traditionally — with CSS in external CSS files, which then pass a string as the className prop to reference them like so:
If you have worked with a large web application, you can attest to the fact that the CSS files begin to get really bulky, clumsy and very complex. One great solution to this is the introduction of SASS and although that helps, it starts to become the same thing with the sheer number of SCSS files a project can have and the abstraction starts to even become complex in itself.
- Inline CSS inside your react components:
This is highly discouraged by React as it is not sustainable nor scalable (more on this later).
This option looks promising, it’s no wonder there is a very fast widespread adoption with over 600k downloads in the past month.
Why you should use styled-components
Freedom to build custom components with CSS
With styled-components, the user interface design focus shifts from just merely styling HTML elements or React components through className to defining styled components that contain their own styles and are so easily reusable across the entire project. So initially a sub-heading declaration which looked like this:
with the styles defined like this:
would become something like this:
The styles become an integral part of the component here, thereby eliminating the key part the CSS classes initially played by removing the mapping between styles and components. This is all built with plain CSS, there is always this feeling of familiarity you get when working with something you are already used to. This feeling has been carefully preserved for every user of styled-components as the syntax is still largely plain CSS.
Inline styling on steroids
Ordinarily, inline styling is discouraged by the react team, a concern that is very valid because inline styles do not allow the use of pseudos and media queries. Also, inline styles should not be used due to a lot of concerns about browser compatibility, camel-casing and automatically appended scalar quantities. But with styled-components, we can see a kind of inline styling but without all the aforementioned inline styling baggage, I call it vibranium power. Here is sample code to demonstrate:
But with styled-components…
We also see how the styled-component attached a style tag on top of the DOM while an inline style just works with the properties of the DOM node instead.
Native mobile support
For teams with a React codebase who also use React Native for mobile development, styled-components is one of the best-unified solutions out there for you. If consistency across platforms is a priority, then you would be glad to find out that styled-components can be bundled into React Native.
In React Native with styled-components, you can just assign alias names to comments making your JSX code very legible. Also, you can convert any component even custom components to a styled component by simply invoking styled().
In the Frontend Tooling world, the team at Vue were (in my opinion) the very first to perfect this concept of scoping styles. There is one very annoying thing about using CSS and that is the fact that for a non-expert CSS user, it gets really frustrating when you change the style of a particular element or class in your stylesheet and it inversely affects another seemingly unrelated element or behaviour in the DOM. This is a great reason to use styled-components as it is component based and very scoped, like Vue.
Styled-components enforces the use of props in the place of classes. This no-class policy has helped them make more developers tow the route of best practices for controlling the behaviour of a component.
Initially, you would write:
But now, it should be like this:
We see how we have managed to keep HTML and CSS manipulations out of the component.
Alternatively, you can always go right back to className, the same results will be achieved.
styled-components supports concurrent server-side rendering, with stylesheet rehydration. The basic idea is that every time you render your app on the server, you can create a Server StyleSheet and add a provider to your react tree, that accepts styles via a context API.
This doesn’t interfere with global styles, such as keyframes or create Global Style and allows you to use styled-components with React DOM’s various SSR APIs.
CSS unit and snapshot testing
Owing to the fact that styled-components are indeed components, unit testing can be run on them. This is a major CSS breakthrough and there is already a jest integration support by the styled-component team.
Jest Styled Components is a set of utilities for testing styled-components with Jest. This package improves the snapshot testing experience and provides a brand new matcher to make expectations on the style rules. It can be installed like this:
Here’s an example of a test:
And here’s an example of the resulting snapshot:
Sass and polished support
If you followed this article to this point, you must have noticed some nested styles, Sass and even Polished, a toolset created by the team to further stretch the powers of Sass:
Supporting Sass exposes the core mission of styled-components and that is to create the perfect CSS-in-JS experience without losing touch with everything we already love about CSS which includes reducing the lines of code and other optimization features of Sass.
Arguments against styled-components
It’s hard for me to come up with very many reasons not to use styled-components (especially given the title of the post), but it would be unfair if I did not also point out some (valid) concerns about CSS-in-JS frameworks in this article.
Some people also indicate the learning curve of styled-components is steep and also the unique differences among CSS-in-JS frameworks. I would strongly recommend using and sticking to styled-components.
Styled-components started about two years ago and React developers always ask what if it stops being supported. You have to make sure you aware of this before using them in production.
People do not like change. This is, in fact, a valid argument as CSS in a separate document is still one of the longest lasting standards in web development.
Some people feel that the styled-components community is small and they might not get enough support and as fast as they might need it when they run into difficult bugs, use cases or errors. This is also valid but you have to put the lock-in nature of styled-components into consideration to understand why.
There is a massively growing community around styled-components with over 22,000 ⭐️on GitHub, mostly coming from React developers which is very encouraging and speaks of the prospects of longevity.
It is also very regularly maintained, you can check out the releases page here. If you are a CSS enthusiast, you can check out this State of CSS Survey that is currently all over the internet. If you enjoyed reading you can follow me here for more articles, happy coding!
Plug: LogRocket, a DVR for web apps
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.