Requirements for a Runtime Theme System
The target application needed themes that users could define themselves, not just pick from a fixed set. Broken into concrete capabilities, the work looks like this:
- Define a theme (background color, font color, buttons, links, etc.)
- Create and save multiple themes
- Select and apply a theme
- Switch themes
- Customize a theme
The implementation uses React and styled-components, with the complete source in the theme-builder repository and a live demo available.
Project Setup and Dependencies
Scaffold the app with create-react-app, then install the libraries the theme system relies on:
npx create-react-app theme-builder
Here the final argument, theme-builder, is the project and folder name. After creation, enter the directory with cd theme-builder. Starting the dev server looks like this:
# Or, npm run start
yarn start
The app is then reachable at http://localhost:3000. create-react-app ships a test file for the App component; since this walkthrough includes no component tests, it can be deleted.
Install the dependencies while setting up:
# Or, npm i ...
yarn add styled-components webfontloader lodash
Each package has a role:
- styled-components provides theming support out of the box through a wrapper component called
<ThemeProvider>, which supplies the theme to every React component wrapped inside it. - Web Font Loader loads fonts from sources such as Google Fonts and Adobe Fonts when a theme is applied.
- lodash supplies small JavaScript utilities.
Theme Data Model and Persistence
A theme is described by four things: a unique identifier, a name, color definitions and fonts. That structure is what the rest of the application consumes; additional properties or a different shape are possible.

To hold several themes, add src/theme/schema.json with two entries, “light” and “sea wave”.
{
"data" : {
"light" : {
"id": "T_001",
"name": "Light",
"colors": {
"body": "#FFFFFF",
"text": "#000000",
"button": {
"text": "#FFFFFF",
"background": "#000000"
},
"link": {
"text": "teal",
"opacity": 1
}
},
"font": "Tinos"
},
"seaWave" : {
"id": "T_007",
"name": "Sea Wave",
"colors": {
"body": "#9be7ff",
"text": "#0d47a1",
"button": {
"text": "#ffffff",
"background": "#0d47a1"
},
"link": {
"text": "#0d47a1",
"opacity": 0.8
}
},
"font": "Ubuntu"
}
}
}
The schema.json contents could live in a database so themes and the current selection persist server-side; for this example they go into the browser's localStorage instead. Create src/utils/storage.js with small helpers for writing to and reading from localStorage:
export const setToLS = (key, value) => {
window.localStorage.setItem(key, JSON.stringify(value));
}
export const getFromLS = key => {
const value = window.localStorage.getItem(key);
if (value) {
return JSON.parse(value);
}
}
The app should seed localStorage on first load. Replace index.js with the following, which reads the themes from schema.json and stores them under the key all-themes:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as themes from './theme/schema.json';
import { setToLS } from './utils/storage';
const Index = () => {
setToLS('all-themes', themes.default);
return(
<App />
)
}
ReactDOM.render(
<Index />
document.getElementById('root'),
);
Restart the app if it was stopped, then confirm in DevTools that the themes appear in localStorage.
Applying a Theme with Hooks and Global Styles
The selected theme object is passed to <ThemeProvider>. A custom React hook in src/theme/useTheme.js tracks which theme is active and whether it was read from storage successfully:
import { useEffect, useState } from 'react';
import { setToLS, getFromLS } from '../utils/storage';
import _ from 'lodash';
export const useTheme = () => {
const themes = getFromLS('all-themes');
const [theme, setTheme] = useState(themes.data.light);
const [themeLoaded, setThemeLoaded] = useState(false);
const setMode = mode => {
setToLS('theme', mode)
setTheme(mode);
};
const getFonts = () => {
const allFonts = _.values(_.mapValues(themes.data, 'font'));
return allFonts;
}
useEffect(() =>{
const localTheme = getFromLS('theme');
localTheme ? setTheme(localTheme) : setTheme(themes.data.light);
setThemeLoaded(true);
}, []);
return { theme, themeLoaded, setMode, getFonts };
};
The hook returns the stored theme plus a boolean indicating a correct load, exposes a setMode function for applying a theme programmatically (used later), and provides the font list for the web font loader.
Site-wide appearance — background, font, button and link styling — belongs in global styles. styled-components' createGlobalStyle produces theme-aware global components; put them in src/theme/GlobalStyles.js:
import { createGlobalStyle} from "styled-components";
export const GlobalStyles = createGlobalStyle`
body {
background: ${({ theme }) => theme.colors.body};
color: ${({ theme }) => theme.colors.text};
font-family: ${({ theme }) => theme.font};
transition: all 0.50s linear;
}
a {
color: ${({ theme }) => theme.colors.link.text};
cursor: pointer;
}
button {
border: 0;
display: inline-block;
padding: 12px 24px;
font-size: 14px;
border-radius: 4px;
margin-top: 5px;
cursor: pointer;
background-color: #1064EA;
color: #FFFFFF;
font-family: ${({ theme }) => theme.font};
}
button.btn {
background-color: ${({ theme }) => theme.colors.button.background};
color: ${({ theme }) => theme.colors.button.text};
}
`;
With that in place, App.js can render a themed page:
// 1: Import
import React, { useState, useEffect } from 'react';
import styled, { ThemeProvider } from "styled-components";
import WebFont from 'webfontloader';
import { GlobalStyles } from './theme/GlobalStyles';
import {useTheme} from './theme/useTheme';
// 2: Create a cotainer
const Container = styled.div`
margin: 5px auto 5px auto;
`;
function App() {
// 3: Get the selected theme, font list, etc.
const {theme, themeLoaded, getFonts} = useTheme();
const [selectedTheme, setSelectedTheme] = useState(theme);
useEffect(() => {
setSelectedTheme(theme);
}, [themeLoaded]);
// 4: Load all the fonts
useEffect(() => {
WebFont.load({
google: {
families: getFonts()
}
});
});
// 5: Render if the theme is loaded.
return (
<>
{
themeLoaded && <ThemeProvider theme={ selectedTheme }>
<GlobalStyles/>
<Container style={{fontFamily: selectedTheme.font}}>
<h1>Theme Builder</h1>
<p>
This is a theming system with a Theme Switcher and Theme Builder.
Do you want to see the source code? <a href="https://github.com/atapas/theme-builder" target="_blank">Click here.</a>
</p>
</Container>
</ThemeProvider>
}
</>
);
}
export default App;
The component does five things:
- It imports the
useStateanduseEffecthooks for state tracking and side effects,ThemeProviderandstyledfrom styled-components,WebFontfor font loading, and the customuseThemehook andGlobalStylescomponent. - It builds a
Containercomponent from CSS styles viastyled. - It declares state variables and watches for changes.
- It loads all fonts the app requires.
- It renders text and a link wrapped entirely in
<ThemeProvider>, which receives the selected theme as a prop, along with<GlobalStyles/>.
On refresh, the default “light” theme should be active. To verify switching, edit useTheme.js and change this line:
localTheme ? setTheme(localTheme) : setTheme(themes.data.light);
…to this:
localTheme ? setTheme(localTheme) : setTheme(themes.data.seaWave);
After another refresh, the “sea wave” theme should render.
Switching Themes Through the UI
Theme switching can be driven by a click, with a preview of each option. Each preview box is a ThemeCard that takes a theme definition as a prop; the switcher loops over all themes and renders one card per theme. The card markup pulls the theme's own color and font properties and applies them:
const ThemeCard = props => {
return(
<Wrapper
style={{backgroundColor: `${data[_.camelCase(props.theme.name)].colors.body}`, color: `${data[_.camelCase(props.theme.name)].colors.text}`, fontFamily: `${data[_.camelCase(props.theme.name)].font}`}}>
<span>Click on the button to set this theme</span>
<ThemedButton
onClick={ (theme) => themeSwitcher(props.theme) }
style={{backgroundColor: `${data[_.camelCase(props.theme.name)].colors.button.background}`, color: `${data[_.camelCase(props.theme.name)].colors.button.text}`, fontFamily: `${data[_.camelCase(props.theme.name)].font}`}}>
{props.theme.name}
</ThemedButton>
</Wrapper>
)
}
Next, create src/ThemeSelector.js with the switcher implementation (full content in the repository) and import it in App.js:
import ThemeSelector from './ThemeSelector';
It is then used inside the Container component:
<Container style={{fontFamily: selectedTheme.font}}>
// same as before
<ThemeSelector setter={ setSelectedTheme } />
</Container>
Any number of themes can be added to schema.json and will appear in the UI as switchable options. The applied theme is written to localStorage as well, so the selection survives closing and reopening the app.
Letting Users Build Their Own Themes
Users may want properties from more than one theme, so the app also offers a small interface for choosing appearance options and saving the result. The theme-creation code is not explained in detail here; the main source file is CreateThemeContent.js, consumed by App.js. The new theme object is assembled from the value of each input element's change event and appended to the collection of theme objects.
Related Approaches
CSS custom properties have made theming systems increasingly common. Examples include Dieter Raber's approach to color with HSL and calc, Chris's roundup of CSS custom properties for theming, Michelle Barker's custom-property setup with Tailwind CSS, and Andrés Galente's pattern of variables, globals and locals. This implementation goes a step further by storing theme properties, switching between them, letting users customize a theme and saving those preferences.



