CSS in JS
CSS in JS gives you the ability to write plain CSS within your components while
removing the possibility of naming collisions with class names. For the purpose of
exploring this option, I will be reviewing the pros and cons of the most popular solution,
Styled Components (https://styled-components.com). It is, however, worth
mentioning that there are many different CSS in JS solutions, including Emotion
(https://emotion.sh) and JSS (https://cssinjs.org).
The pros for using Styled Components are as follows:
• One source of truth: Like Tailwind, Styled Components also removes contextswitching, as your CSS code is housed within the same file as the component
making use of it.
• Styles tied to components: Styles are created for use by one specific component
and are located next to the markup that implements them. As such, you know
exactly what makes use of these styles but, more importantly, you know that
editing these styles will only affect the markup located with them.
32 Styling Choices and Creating Reusable Layouts
• JS in CSS: We can make use of JS inside our CSS to determine styling. This makes
handling conditionals within styles much easier, as we do not have to create two
different class names and use a ternary operator.
• Extending: It can often be the case that you may want to use a component style
but subtly modify it for a different use case. Instead of copying the styles again and
creating a new component from the ground up, we can instead create a component
that inherits the styling of another.
The cons for using Styled Components are as follows:
• Performance: When parsing your styles into plain CSS, Styled Components adds
these as style tags in the head of your index.html. Styles used across all your
pages are pulled in on every page without any way to easily split them. Even
caching the styles is difficult, as class names are dynamically generated and can,
therefore, change between builds.
If you like a single source of truth, Styled Components improves the legibility of your
markup when you are combining everything into one file. While performance is listed
as a con, this is something that the community behind Styled Components is making an
effort to improve.
CSS in JS