JavaScript and React course ยท Module 14: Advanced Styling

Theming in Styled-components - Galactic Design System

6 min read ยท
In this lesson7

Imagine a fleet in which every ship has a different shade of purple on its alarm buttons, because every engineer typed the color from memory. When command decides to change the fleet colors, someone will have to search hundreds of files and fix every #7c4dff value by hand. That's what a project without a theme looks like. ThemeProvider in styled-components lets you create a consistent system of colors, sizes, and typography - like a unified interface for an entire space fleet.

Before we start, one honest note. In March 2025 the library's maintainer announced that styled-components is entering maintenance mode: it gets bug fixes but no new features, and the author himself does not recommend it for new projects. The library (currently version 6) still runs in a huge number of existing applications, so it's worth knowing, and the idea of a theme you'll learn here carries over one to one to CSS Variables and other tools.

ThemeProvider

ThemeProvider is a component that provides a theme to all components inside it. Under the hood it uses React context, so the theme reaches any depth without passing props. The theme itself is a plain JavaScript object, in which we group values by category: colors, spacing, border radii and font sizes:

import { ThemeProvider } from 'styled-components';

const spaceTheme = {
  colors: {
    primary: '#7c4dff',
    secondary: '#64b5f6',
    background: '#0a0a2e',
    surface: '#1a1a4e',
    text: '#e0e0e0',
    success: '#00e676',
    warning: '#ffa726',
    danger: '#f44336',
  },
  spacing: {
    xs: '4px',
    sm: '8px',
    md: '16px',
    lg: '24px',
    xl: '32px',
  },
  borderRadius: {
    sm: '4px',
    md: '8px',
    lg: '12px',
    round: '50%',
  },
  fontSize: {
    sm: '12px',
    md: '16px',
    lg: '20px',
    xl: '28px',
  },
};

function App() {
  return (
    <ThemeProvider theme={spaceTheme}>
      <Dashboard />
    </ThemeProvider>
  );
}

ThemeProvider renders nothing in the DOM and doesn't change how Dashboard looks on its own. It only makes the object available, and components have to use it. You invent key names such as colors or spacing yourself, the library doesn't impose any structure.

Using the Theme in Components

Every styled-component automatically has access to the theme via props.theme. Inside the style template you insert a function in ${...}, and the library calls it with the component's props:

const Panel = styled.div`
  background: ${props => props.theme.colors.surface};
  border-radius: ${props => props.theme.borderRadius.lg};
  padding: ${props => props.theme.spacing.lg};
  color: ${props => props.theme.colors.text};
`;

const Heading = styled.h2`
  color: ${({ theme }) => theme.colors.primary};
  font-size: ${({ theme }) => theme.fontSize.xl};
  margin-bottom: ${({ theme }) => theme.spacing.md};
`;

Note the destructuring - ({ theme }) is shorthand for (props) => props.theme. Both forms work identically, but I recommend the second one, because with many values it's shorter and more readable. Neither of these components contains a single hardcoded color any more.

Switching Themes (Dark/Light)

One of the most popular uses of ThemeProvider is switching between dark and light themes. We define two objects with the same keys, and the isDark state picks which one goes to the provider:

const darkTheme = {
  colors: {
    background: '#0a0a2e',
    surface: '#1a1a4e',
    text: '#e0e0e0',
    primary: '#7c4dff',
  },
};

const lightTheme = {
  colors: {
    background: '#f5f5f5',
    surface: '#ffffff',
    text: '#212121',
    primary: '#5c6bc0',
  },
};

function App() {
  const [isDark, setIsDark] = useState(true);
  const theme = isDark ? darkTheme : lightTheme;

  return (
    <ThemeProvider theme={theme}>
      <AppContainer>
        <button onClick={() => setIsDark(!isDark)}>
          Toggle Theme
        </button>
        <Dashboard />
      </AppContainer>
    </ThemeProvider>
  );
}

After the click, only the object passed to theme changes, and all styled-components recompute their styles. The component code stays untouched. This only works when both themes have identical keys, because a missing key means undefined in the CSS.

Global Styles

createGlobalStyle lets you define global CSS styles that also have access to the theme. It returns a component that you render once, inside ThemeProvider:

import { createGlobalStyle } from 'styled-components';

const GlobalStyles = createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  body {
    background: ${({ theme }) => theme.colors.background};
    color: ${({ theme }) => theme.colors.text};
    font-family: 'Segoe UI', sans-serif;
  }
`;

function App() {
  return (
    <ThemeProvider theme={spaceTheme}>
      <GlobalStyles />
      <Dashboard />
    </ThemeProvider>
  );
}

GlobalStyles must sit inside the provider, otherwise theme would be empty. Thanks to that, the background of the whole page changes together with the theme, not just the background of individual panels.

The useTheme Hook

If you need access to the theme in component logic (not just in styles), use the useTheme hook. It returns the same object you passed to the provider:

import { useTheme } from 'styled-components';

function StatusChart({ data }) {
  const theme = useTheme();

  // Use theme colors in logic, e.g. for Canvas, SVG, or conditions
  const chartColor = data.isHealthy
    ? theme.colors.success
    : theme.colors.danger;

  return (
    <div>
      <svg width="100" height="100">
        <circle cx="50" cy="50" r="40" fill={chartColor} />
      </svg>
      <p style={{ color: theme.colors.text }}>
        Status: {data.isHealthy ? 'OK' : 'Alert'}
      </p>
    </div>
  );
}

useTheme is useful when you need theme values outside of styled-components - for example, for drawing on Canvas, configuring chart libraries, or conditional logic based on theme colors.

Nested Themes

ThemeProvider can be nested so that different sections of the application have different themes. The nearest provider wins:

function App() {
  return (
    <ThemeProvider theme={darkTheme}>
      <Header />
      <ThemeProvider theme={lightTheme}>
        <ContentArea />  {/* lightTheme applies here */}
      </ThemeProvider>
      <Footer />  {/* darkTheme applies again here */}
    </ThemeProvider>
  );
}

It's like different sections of a spaceship with different lighting modes - the command bridge can be dark while the laboratory is bright. The inner provider can also receive a function theme={outer => ({ ...outer, ... })}, which extends the outer theme instead of replacing it.

Theming Best Practices

  1. Centralize colors and sizes - never hardcode values in components, always reference the theme
  2. Use TypeScript - define a type for your theme to get autocompletion (in styled-components you extend the DefaultTheme interface)
  3. Maintain consistency - all themes should have the same keys (colors, spacing, fontSize)
  4. Test both themes - make sure every component looks good in both dark and light modes

In the next lesson you'll see responsive patterns, and in the main project you'll combine this theme with CSS Modules and Tailwind in a single mission dashboard.

Remember: a theme is the fleet's shared palette, you change it in one place and every ship immediately shines in the new colors.

Code for this lesson: App.jsx
import React, { useState } from 'react';
import styled, { ThemeProvider, createGlobalStyle } from 'styled-components';

// Two themes -- dark (cosmic) and light
const darkTheme = {
  colors: {
    primary: '#7c4dff',
    secondary: '#64b5f6',
    background: '#0a0a2e',
    surface: '#1a1a4e',
    text: '#e0e0e0',
    textMuted: '#9e9e9e',
    border: '#3949ab',
    success: '#00e676',
    warning: '#ffa726',
    danger: '#f44336',
  },
  spacing: { xs: '4px', sm: '8px', md: '16px', lg: '24px', xl: '32px' },
  borderRadius: { sm: '4px', md: '8px', lg: '12px' },
  fontSize: { sm: '12px', md: '16px', lg: '20px', xl: '28px' },
};

const lightTheme = {
  colors: {
    primary: '#5c6bc0',
    secondary: '#1976d2',
    background: '#f5f5f5',
    surface: '#ffffff',
    text: '#212121',
    textMuted: '#757575',
    border: '#e0e0e0',
    success: '#4caf50',
    warning: '#ff9800',
    danger: '#f44336',
  },
  spacing: darkTheme.spacing,
  borderRadius: darkTheme.borderRadius,
  fontSize: darkTheme.fontSize,
};

const GlobalStyles = createGlobalStyle`
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    background: ${({ theme }) => theme.colors.background};
    color: ${({ theme }) => theme.colors.text};
    font-family: 'Segoe UI', sans-serif;
    transition: background 0.3s ease, color 0.3s ease;
  }
`;

const Container = styled.div`
  max-width: 600px;
  margin: 0 auto;
  padding: ${({ theme }) => theme.spacing.lg};
`;

const Header = styled.header`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: ${({ theme }) => theme.spacing.xl};
`;

const Title = styled.h1`
  color: ${({ theme }) => theme.colors.primary};
  font-size: ${({ theme }) => theme.fontSize.xl};
`;

const ThemeToggle = styled.button`
  padding: ${({ theme }) => theme.spacing.sm} ${({ theme }) => theme.spacing.md};
  background: ${({ theme }) => theme.colors.surface};
  color: ${({ theme }) => theme.colors.text};
  border: 2px solid ${({ theme }) => theme.colors.border};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  cursor: pointer;
  font-size: ${({ theme }) => theme.fontSize.md};
  transition: all 0.2s ease;
  &:hover { border-color: ${({ theme }) => theme.colors.primary}; }
`;

const Card = styled.div`
  background: ${({ theme }) => theme.colors.surface};
  border: 1px solid ${({ theme }) => theme.colors.border};
  border-radius: ${({ theme }) => theme.borderRadius.lg};
  padding: ${({ theme }) => theme.spacing.lg};
  margin-bottom: ${({ theme }) => theme.spacing.md};
  transition: all 0.3s ease;
`;

const CardTitle = styled.h3`
  color: ${({ theme }) => theme.colors.primary};
  margin-bottom: ${({ theme }) => theme.spacing.sm};
`;

const Badge = styled.span`
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: ${({ theme }) => theme.fontSize.sm};
  font-weight: bold;
  background: ${({ theme, variant }) =>
    variant === 'success' ? theme.colors.success + '33' :
    variant === 'warning' ? theme.colors.warning + '33' :
    theme.colors.danger + '33'};
  color: ${({ theme, variant }) =>
    variant === 'success' ? theme.colors.success :
    variant === 'warning' ? theme.colors.warning :
    theme.colors.danger};
`;

export default function App() {
  const [isDark, setIsDark] = useState(true);

  return (
    <ThemeProvider theme={isDark ? darkTheme : lightTheme}>
      <GlobalStyles />
      <Container>
        <Header>
          <Title>Theme Demo</Title>
          <ThemeToggle onClick={() => setIsDark(!isDark)}>
            {isDark ? 'Light' : 'Dark'}
          </ThemeToggle>
        </Header>

        <Card>
          <CardTitle>Ion engines</CardTitle>
          <p>Status: <Badge variant="success">Active</Badge></p>
          <p style={{ marginTop: '8px', fontSize: '14px' }}>
            Full power -- ready for the hyperspace jump.
          </p>
        </Card>

        <Card>
          <CardTitle>Energy shields</CardTitle>
          <p>Status: <Badge variant="warning">Warning</Badge></p>
          <p style={{ marginTop: '8px', fontSize: '14px' }}>
            Energy level: 42%. Recharge required.
          </p>
        </Card>

        <Card>
          <CardTitle>Life support system</CardTitle>
          <p>Status: <Badge variant="danger">Critical</Badge></p>
          <p style={{ marginTop: '8px', fontSize: '14px' }}>
            Oxygen reserves for 72h. Immediate intervention required!
          </p>
        </Card>
      </Container>
    </ThemeProvider>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the role of the ThemeProvider component in styled-components?

  2. 2. What is createGlobalStyle used for in styled-components?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the elements in the correct ThemeProvider hierarchy:

  • Code editor

    Implement theme switching with ThemeProvider

  • Click in order

    Arrange the syntax for accessing the primary color from the theme in a styled-component:

  • Code editor

    Implement navigation with dynamic active link styling

  1. QuestionThemeProvider in styled-components
  2. Put in orderThemeProvider Hierarchy
  3. Coding taskPractice: Theme Switcher
  4. QuestioncreateGlobalStyle in styled-components
  5. Click in orderAccessing the Theme in styled-components
  6. Coding taskPractice: styled-components Navigation

Useful articles