React 101 — CSS-in-JS Basics

Tony
6 min readJul 31, 2024

Web frontend development requires CSS to define styles, and as applications are broken down into components, CSS also needs to be componentized.

In the previous my-kanban project, you have already seen how to import CSS files into JS (JSX) files.

import './App.css';

You might wonder if having one CSS file per JSX file constitutes componentized CSS. Actually, it’s not quite enough. CSS and JS are inherently heterogeneous, making it difficult for CSS to correspond precisely to React’s component hierarchy. Additionally, it is crucial to ensure style isolation between different components.

So, we have the following issues that need to be addressed:

  • How can we define styles for React components to achieve symbiosis between styles and components?
  • How can we prevent CSS from different components from affecting each other?
  • How can we use props or state values in CSS?

To solve these issues, the frontend community, especially the React community, has introduced numerous CSS-in-JS frameworks over time. In this article, I will use the popular Emotion library as an example to introduce the characteristics of CSS-in-JS and the important considerations when using it.

What is CSS-in-JS?

--

--