Course contentsShow
← React
Lesson 1923 of 2,39644. Styling ApproachesFree lesson

styled-components Basics: Tagged Template Literals

Creating styled components with tagged templates: `styled.div` syntax, nesting, and how styles become actual components.

styled-components Basics: Tagged Template Literals

You'll learn how styled-components uses JavaScript's tagged template literal syntax to turn CSS into actual React components.

The Core Idea

styled-components leverages a special JavaScript feature called tagged template literals. Instead of writing CSS in separate files, you write it directly in your JavaScript using backticks after styled.element. This CSS magically becomes a fully functional React component that you can render like any other.

Here's the fundamental syntax:

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
`;

// Now Button is a React component!
<Button>Click me</Button>

Why Tagged Templates?

The styled.button part is actually a function call. The backticks that follow aren't a normal string—they're a tagged template literal, which passes the CSS text (and any interpolated values) to styled-components' processing engine. This engine generates a unique class name, injects the styles into the DOM, and returns a component.

Nesting Like Regular CSS

styled-components supports nesting just like preprocessors:

const Card = styled.div`
  padding: 20px;
  background: white;

  &:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  h2 {
    margin-top: 0;
  }
`;

The & references the component itself, and you can nest child element styles directly.

Think of It as CSS That Returns Components

The beautiful part: your styled definition is your component. No separate import of CSS, no className juggling—the styles and the element are unified into one reusable piece.

Key Takeaway: styled-components uses tagged template literals to transform CSS strings into React components with scoped styles, combining the styling and component definition in one declaration.