Styled Components

6.4.0 · active · verified Sun Apr 19

Styled Components is a popular JavaScript library for styling React components using tagged template literals and CSS. It allows developers to write actual CSS code to style components, abstracting away the styling into reusable, themeable components. Currently at stable version 6.4.0, it maintains an active release cadence with frequent patch releases and minor updates addressing bugs, performance, and compatibility with new React features like Server Components (RSC) and React 19. Key differentiators include its powerful theming capabilities, robust server-side rendering support, and the ability to automatically prefix CSS, making it a powerful alternative to traditional CSS modules or utility-first CSS frameworks. It aims to provide a seamless developer experience by keeping styling close to the component logic.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a global style, defining a basic styled button with props, applying conditional CSS using the `css` helper, and utilizing a `ThemeProvider` to manage design tokens across components.

import styled, { ThemeProvider, createGlobalStyle, css } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
      sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
`;

const Button = styled.button`
  background: ${props => props.primary ? props.theme.colors.primary : 'white'};
  color: ${props => props.primary ? 'white' : props.theme.colors.primary};
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid ${props => props.theme.colors.primary};
  border-radius: 3px;

  ${props => props.size === 'large' && css`
    font-size: 1.2em;
    padding: 0.5em 1.5em;
  `}
`;

const theme = {
  colors: {
    primary: '#007bff',
    secondary: '#6c757d'
  }
};

function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div>
        <Button>Normal Button</Button>
        <Button primary>Primary Button</Button>
        <Button primary size="large">Large Primary Button</Button>
      </div>
    </ThemeProvider>
  );
}

export default App;

view raw JSON →