What is CSS-in-JS?

CSS-in-JS is a pattern where CSS is composed and managed inside your JavaScript code instead of in external .css files. This technique is especially popular in component-based frameworks like React.

Why Use It? The main benefit is scoped styles. When you create a styled component, the library generates a unique class name for it. This means the styles you write for one component will never accidentally leak out and affect other components. This completely eliminates a huge category of CSS bugs.

Other benefits include:

  • Dynamic Styling: Easily change styles based on component props.
  • Co-location: Your styles live in the same file as your component logic, making them easier to maintain.
  • Dead Code Elimination: Bundlers can easily determine which styles are unused and remove them.

Getting Started with styled-components

Let's see it in action. First, you'd install it in your React project: npm install styled-components.

styled-components uses a feature called "Tagged Template Literals" to create components. You define your styles inside backticks (`).

Code Snippet: Creating a Styled Button

Let's create a Button component that can be a standard button or a "primary" one based on a prop.

JavaScript (React Component):

JavaScript


import React from 'react';
import styled, { css } from 'styled-components';

// 1. Create a styled component. This will render a <button> tag.
const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid #BF4F74;
  color: #BF4F74;
  margin: 0.5em 1em;
  padding: 0.25em 1em;
  font-size: 1em;
  cursor: pointer;

  /* 2. Adapt styles based on props! */
  ${props => props.primary && css`
    background: #BF4F74;
    color: white;
  `}
`;

// 3. Use your new component like any other React component.
const App = () => (
  <div>
    <Button>Normal Button</Button>
    <Button primary>Primary Button</Button>
  </div>
);

export default App;

When this code runs, styled-components will generate a <button> element with a unique class name and inject the corresponding styles into the <head> of your document. The "Primary Button" will get additional styles because its primary prop is true.

Note: While styled-components is very popular, Emotion is another excellent library in this space with a very similar API and feature set.