CSS-in-JS - Moving Styles Into Javascript

Expand your knowledge of CSS further and learn how to use libraries and template literals in order to style React components within JS.

What is CSS-in-JS?

We already mentioned in the introduction that CSS-in-JS is a bit of a hotly debated topic. Opponents say that users of CSS-in-JS simply do not understand the cascade to write scalable CSS. Proponents, on the other hand, explain that the cascade is not the main reason for choosing CSS-in-JS but argue that a safer way is needed to write highly isolated components. However, there could be room and reasons for both. CSS-in-JS certainly has a reason to exist. But what even is CSS-in-JS?

The CSS-in-JS approach mandates that the styles that are commonly found in CSS files are now moved into JavaScript. As was already the case in CSS modules, the primary goal is to create highly isolated components free of conflict, making them easy to reuse throughout the application. However, as opposed to CSS modules, the styling in CSS-in-JS happens entirely in JavaScript. The syntax is very similar, and it mostly feels like you’re writing regular CSS.

CSS-in-JS is the umbrella term for the concept, whereas the actual implementation is achieved by a number of different libraries. If you are looking for a great overview, Please check out this site. It covers over 60 different libraries that can help you to implement your own CSS-in-JS solution.

Styled components

Let’s talk about styled components now, which is the most popular library with around 23,000 stars on GitHub. order to use it, we need to first install it via the command line:

npm install styled-components

Or:

yarn add styled-components

Once installed, we are ready to import it and write our first styled component. Using the styled function, we define the HTML element that we want to style. Template literal syntax from ES2015 is used to define the CSS for our styled component.

To create a button that is black and yellow, we would need to write the following:

Get hands-on with 1400+ tech skills courses.