React Styling

Styled Components

CSS-in-JS, dynamic styles, theming, global styles, and server-side rendering.

Advertisement

Styled Components

CSS-in-JS, dynamic styles, theming, global styles, and server-side rendering.

Overview

Styled-components lets you write actual CSS in JavaScript with component-level scoping.

Key Concepts

  • Template Literals — Write CSS in tagged template literals
  • Dynamic Props — Pass props to change styles dynamically
  • Theme Provider — Share theme across all styled components
  • Global Styles — Inject global CSS reset or base styles
  • SSR Support — Server-side rendering with style collection

Code Examples

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

const Button = styled.button`
  background: ${props => props.primary ? '#007bff' : 'white'};
  color: ${props => props.primary ? 'white' : '#007bff'};
  padding: 10px 20px;
  border: 2px solid #007bff;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;

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

const GlobalStyle = createGlobalStyle`
  body { margin: 0; font-family: sans-serif; }
`;

function App() {
  return (
    <ThemeProvider theme={{ primary: '#007bff', secondary: '#6c757d' }}>
      <GlobalStyle />
      <Button primary>Primary</Button>
      <Button>Secondary</Button>
    </ThemeProvider>
  );
}

Practice

Create a themed component library with dark mode support using styled-components.