0Pricing
Frontend Academy · Lesson

CSS-in-JS: Styled-components and Emotion

Write component styles as tagged template literals with styled-components or the css prop with Emotion, and use props for dynamic styles.

What Is CSS-in-JS?

CSS-in-JS writes component styles directly in JavaScript/TypeScript. Styles are co-located with components, support dynamic values from props, and are automatically scoped. The two most popular libraries are styled-components and Emotion.

Styled-components Basics

Use tagged template literals to define styled components. The result is a React component that renders an HTML element with the styles applied.

import styled from 'styled-components';

const Button = styled.button`
  background: ${props => props.primary ? '#6366f1' : 'white'};
  color: ${props => props.primary ? 'white' : '#6366f1'};
  padding: 8px 16px;
  border: 2px solid #6366f1;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    opacity: 0.9;
  }
`;

<Button primary>Primary</Button>
<Button>Outline</Button>

All lessons in this course

  1. BEM Methodology: Block Element Modifier
  2. CSS Modules: Scoped Class Names
  3. CSS-in-JS: Styled-components and Emotion
  4. Tailwind CSS Utility-First Approach
← Back to Frontend Academy