Styled Components: CSS-in-JS as Components
Think of your styles as React components. Styled Components uses JavaScript template literals to write CSS in your JS, creating components with encapsulated styles. It's ideal for building design systems where styles change based on props.
WHY IT EXISTS: Traditional CSS has a global scope, which leads to class name collisions and makes it hard to manage styles in large, component-based applications. Styled Components was created to colocate styles directly with the components that use them, eliminating global scope issues and making styling more modular and predictable.
THE MENTAL MODEL: Think of your styles as components themselves. Instead of writing CSS in a separate file and mapping class names to your JSX (like ), you define a new component that is the style. You would create and use a <Title> component that has all its necessary CSS encapsulated within it, making your markup more semantic.
HOW IT WORKS: Styled Components uses a JavaScript feature called tagged template literals. You import styled from the library and use it like a function tag, for example styled.div, followed by backticks containing your CSS rules. This returns a React component that renders a div with the styles you defined. The library automatically generates unique class names to prevent style collisions. You can also embed functions within the CSS to adapt styles based on the component's props.
WHEN TO USE IT: Use Styled Components when building a component-based application in React, especially when creating a design system. It excels at creating reusable, themeable components whose styles are dynamic and dependent on their state or props. It's also great for teams that prefer to keep all component-related code—logic, template, and styles—in a single file.
WHEN NOT TO USE IT: Avoid it if your project requires zero-runtime CSS-in-JS, as it does have a small performance overhead from generating styles at runtime. For highly static sites, traditional CSS files might be more performant and easier to cache. If your team has a strong preference for a strict separation of concerns between CSS, HTML, and JS, this approach will feel unnatural.
ONE CANONICAL EXAMPLE: To create a styled button, you would write: const Button = styled.button\background: {props => props.primary ? 'palevioletred' : 'white'}; color: {props => props.primary ? 'white' : 'palevioletred'}; border: 2px solid palevioletred; padding: 8px;\;. Then, in your app, you can use it like a regular component: <Button>Click Me</Button> or <Button primary>Primary Action</Button>. The component's styles will change based on whether the primary prop is present.
Read the original → styled-components.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.