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

Organizing Theme Tokens in JavaScript

Structure theme values as JavaScript objects and map them to CSS variables for maintainability and type safety.

Organizing Theme Tokens in JavaScript

What you'll learn: How to structure your design tokens as JavaScript objects and automatically map them to CSS variables for a scalable, type-safe theming system.

Why Organize Tokens?

You've already seen how to use CSS variables for themes, but hardcoding variable names like --color-primary-500 everywhere becomes messy fast. By organizing your theme tokens as JavaScript objects, you create a single source of truth that's easier to maintain, refactor, and type-check.

Think of it like a dictionary: instead of scattering words throughout your codebase, you keep them all in one organized reference book.

Structuring Theme Objects

Create a centralized theme configuration:

// theme.js
export const lightTheme = {
  colors: {
    primary: '#3b82f6',
    background: '#ffffff',
    text: '#1f2937',
  },
  spacing: {
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
  },
  fonts: {
    body: 'system-ui, sans-serif',
    heading: 'Georgia, serif',
  },
};

export const darkTheme = {
  colors: {
    primary: '#60a5fa',
    background: '#1f2937',
    text: '#f9fafb',
  },
  spacing: lightTheme.spacing, // Share non-color tokens
  fonts: lightTheme.fonts,
};

Mapping to CSS Variables

Convert your objects into CSS custom properties programmatically:

function applyTheme(theme) {
  Object.entries(theme.colors).forEach(([key, value]) => {
    document.documentElement.style.setProperty(`--color-${key}`, value);
  });
  
  Object.entries(theme.spacing).forEach(([key, value]) => {
    document.documentElement.style.setProperty(`--spacing-${key}`, value);
  });
}

// In your theme toggle component:
applyTheme(isDark ? darkTheme : lightTheme);

Now your CSS uses predictable variable names while JavaScript maintains the actual values.

Key Takeaway: Organizing theme tokens as JavaScript objects creates a maintainable, centralized design system that programmatically generates CSS variables—combining the benefits of static typing with runtime flexibility.