How to Let Users Choose the Site Color in React
To let users choose the site's main color, I put the color into one CSS variable (here, --accent) and set the chosen value as a CSS variable on <html>. The React component only handles the currently selected color. The CSS builds the button and heading colors from the variable. The chosen color is saved to localStorage, and on the next visit, a small script that runs before React restores it.
The code in this article was checked by opening the production build in Chromium. I tested clicking and keyboard operation of the radio buttons, reloading, and interaction with another tab.
In my test environment I used Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. The versions were React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and operated the page with Playwright. I also opened the same page in a development build with StrictMode enabled, chose colors, and confirmed that React printed no warnings. I did not test Firefox, Safari, mobile browsers, or frameworks such as Next.js.

- 1. Put the color in one CSS variable and derive the other colors with color-mix()
- 2. Keep the chosen color in a small store outside React
- 3. Build the picker from radio buttons
- 4. Choose white or dark text to match the background
- 5. Prevent the previous color from flashing on reload
- 6. Don't use the localStorage value as-is
Put the color in one CSS variable and derive the other colors with color-mix()
In the CSS, the selectable color is a single variable, --accent. The text color placed on top of the background is --on-accent. For how to use CSS variables, see MDN's Using CSS custom properties.
:root { --accent: #00c8e8; --on-accent: #1f2a30; }
body { margin: 0; font: 15px/1.6 'Noto Sans CJK JP', sans-serif; color: #1f2a30;
background: color-mix(in srgb, var(--accent) 12%, white); }
.site-header { background: var(--accent); color: var(--on-accent); padding: 12px 16px; font-weight: bold; font-size: 17px; }
.card h2 { color: color-mix(in srgb, var(--accent) 70%, black); font-size: 17px; margin: 8px 0 4px; }
.primary { background: var(--accent); color: var(--on-accent); border: 0; border-radius: 6px; padding: 6px 18px; font: inherit; }
The light background color and the dark heading color are made by mixing white or black into --accent with color-mix(). This way, when the user changes the one color, the light and dark shades change together. You don't need to prepare a light and a dark version for each selectable color.
In my test, when I picked pink (#ea7896), the top bar's background became rgb(234, 120, 150). The page background and headings changed to pink mixed with white or black. When read with getComputedStyle, a color made with color-mix() came back not as rgb() but in a form like color(srgb 0.990118 0.936471 0.950588). When comparing colors in tests, watch for this difference in format.
Keep the chosen color in a small store outside React
The chosen color is tied to things outside React: localStorage and the CSS variables on <html>. I also want the color to follow changes made in other tabs. So I kept the color not in component state but in a module-level variable. React reads it with useSyncExternalStore.
First, the functions that read the saved color and put it into a CSS variable.
import { textColorOn } from './contrast';
export const COLORS = [
{ label: '水色', value: '#00c8e8' },
{ label: 'ピンク', value: '#ea7896' },
{ label: '緑', value: '#2b7a3b' },
{ label: '紫', value: '#6c4bc4' },
] as const;
export const DEFAULT_COLOR = '#00c8e8';
const STORAGE_KEY = 'theme-color';
const HEX = /^#[0-9a-f]{6}$/;
// localStorage values can be changed, so only use them when they're in #rrggbb form.
export function readStoredColor(): string {
try {
const v = localStorage.getItem(STORAGE_KEY)?.toLowerCase();
if (v && HEX.test(v)) return v;
} catch {
// In browsers where localStorage is disabled, use the default color.
}
return DEFAULT_COLOR;
}
// Set CSS variables on <html>. Color users read them with things like var(--accent).
export function applyThemeColor(color: string) {
const root = document.documentElement.style;
root.setProperty('--accent', color);
root.setProperty('--on-accent', textColorOn(color));
}
style.setProperty() sets the CSS variable in the style attribute of <html>. As MDN's specificity explanation says, values in the style attribute take precedence over normal rules written in CSS files. That means they can override the default values written on :root. textColorOn is a function that picks the text color to match the background. I explain it in a later section.
Next, the store and the hook.
import { useSyncExternalStore } from 'react';
import { applyThemeColor, DEFAULT_COLOR, readStoredColor } from './theme';
let current = readStoredColor();
const listeners = new Set<() => void>();
function emit() {
for (const l of listeners) l();
}
function subscribe(listener: () => void) {
listeners.add(listener);
// If the color changes in another tab, apply it to this tab too.
const onStorage = (e: StorageEvent) => {
if (e.key !== 'theme-color' && e.key !== null) return;
current = readStoredColor();
applyThemeColor(current);
emit();
};
window.addEventListener('storage', onStorage);
return () => {
listeners.delete(listener);
window.removeEventListener('storage', onStorage);
};
}
export function setThemeColor(color: string) {
current = color;
try {
localStorage.setItem('theme-color', color);
} catch {
// Even if it can't be saved, keep using the chosen color while the page is open.
}
applyThemeColor(color);
emit();
}
export function useThemeColor() {
return useSyncExternalStore(subscribe, () => current, () => DEFAULT_COLOR);
}
setThemeColor puts all the color-change work in one place. It updates the variable, saves to localStorage, sets the CSS variable, and notifies the components that use the hook. Because the CSS variable is set during the change itself, the color changes right after the press.
The storage event fires when another tab on the same origin rewrites localStorage. It does not fire in the tab that made the change. So changes made in this tab are announced with emit(), and changes from other tabs are received through the storage event.
In my test, I opened two tabs in the same browser and chose green in the first tab. The second tab also turned green, and its radio button moved to green. When I called localStorage.clear() in the first tab, the storage event that reached the second tab had e.key set to null, and the color went back to the default light blue. The e.key !== null condition is there for this case.
Build the picker from radio buttons
Since the user picks one of several colors, I made the control a set of radio buttons with the same name. As MDN's <input type="radio"> page explains, radio buttons with the same name form one group, and only one of them can be selected. The color circles are decorative, so I added aria-hidden to hide them from screen readers, and the color names are written as text.
import { COLORS } from './theme';
import { setThemeColor, useThemeColor } from './useThemeColor';
export function ThemeColorPicker() {
const color = useThemeColor();
const isPreset = COLORS.some((c) => c.value === color);
return (
<fieldset className="picker">
<legend>サイトの色</legend>
{COLORS.map((c) => (
<label key={c.value} className="swatch">
<input
type="radio"
name="theme-color"
value={c.value}
checked={color === c.value}
onChange={() => setThemeColor(c.value)}
/>
<span className="dot" style={{ background: c.value }} aria-hidden="true" />
{c.label}
</label>
))}
<label className="swatch">
<input type="color" value={color} onChange={(e) => setThemeColor(e.target.value)} />
{isPreset ? '自分で選ぶ' : `自分で選んだ色(${color})`}
</label>
</fieldset>
);
}
Radio buttons also work with the keyboard. In my test, I focused the pink button and pressed the → key once. It moved to green, and pressing it again moved to purple. Each time, --accent changed too. Because onChange is also called when the selection moves with the keys, the same handler covers both click and keyboard.
The last <input type="color"> is for people who want a color outside the preset list. Playwright cannot operate the color selection dialog, so in the test I put #1d3a8a directly into the input. Then --accent became #1d3a8a, and no radio button was selected.
Choose white or dark text to match the background
When a user picks a dark color, the dark text on the top bar and buttons becomes hard to read. So I calculate which of white or the dark color (#1f2a30) reads better on the background, and put the result into --on-accent. The calculation uses the WCAG formulas for relative luminance and contrast ratio.
// Using WCAG relative luminance and contrast ratio, pick the text color to place on top of the background color.
function channel(v: number): number {
const c = v / 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}
export function luminance(hex: string): number {
const n = parseInt(hex.slice(1), 16);
return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255);
}
export function contrast(a: string, b: string): number {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
// Returns whichever of white or a dark color has the higher contrast ratio against the background.
export function textColorOn(bg: string): string {
return contrast(bg, '#ffffff') >= contrast(bg, '#1f2a30') ? '#ffffff' : '#1f2a30';
}
The results below cover the four preset colors. They also include two colors I added as examples of colors a user might pick with the color input, yellow and navy. Finally, there are two medium-brightness colors, pink and green, for comparison.
水色 #00c8e8: 白との比 2.01 / #1f2a30 との比 7.28 → 文字の色 #1f2a30(4.5 以上)
ピンク #ea7896: 白との比 2.75 / #1f2a30 との比 5.32 → 文字の色 #1f2a30(4.5 以上)
緑 #2b7a3b: 白との比 5.32 / #1f2a30 との比 2.76 → 文字の色 #ffffff(4.5 以上)
紫 #6c4bc4: 白との比 6.10 / #1f2a30 との比 2.40 → 文字の色 #ffffff(4.5 以上)
黄色(自分で選んだ例) #f5d000: 白との比 1.51 / #1f2a30 との比 9.71 → 文字の色 #1f2a30(4.5 以上)
紺(自分で選んだ例) #1d3a8a: 白との比 10.37 / #1f2a30 との比 1.41 → 文字の色 #ffffff(4.5 以上)
明るさが中くらいのピンク(届かない例) #d85878: 白との比 3.76 / #1f2a30 との比 3.90 → 文字の色 #1f2a30(4.5 未満)
明るさが中くらいの緑(届かない例) #2f9e44: 白との比 3.45 / #1f2a30 との比 4.26 → 文字の色 #1f2a30(4.5 未満)
In the GIF at the top, when pink is selected, the text on the top bar and buttons is dark. When purple and green are selected, it is white.
WCAG level AA Success Criterion 1.4.3 requires a contrast ratio of at least 4.5:1 between text and its background (3:1 for large text). All four preset colors reach 4.5 or more with either white or the dark text.
However, some medium-brightness colors cannot reach 4.5 just by switching the text color. In the results above, the pink (#d85878) and the green (#2f9e44) fall short of 4.5 with either white or the dark text. The preset pink (#ea7896) is a lightened version of that pink, chosen so the dark text reaches 4.5 or more. The preset green (#2b7a3b) is a darkened version of that green, chosen so the white text reaches 4.5 or more. When you decide which colors to offer, check them with this calculation. For colors that fall short, make them a little darker or lighter until the ratio is reached.
Some medium-brightness colors do not reach 4.5:1 even when the text color is switched. Choose the colors you offer so that each one reaches at least 4.5:1 with either white or the dark text.
Prevent the previous color from flashing on reload
If the code that restores the saved color exists only in the React code, the default light blue from the CSS is shown until the JS loads and runs. When HTML rendered by the server is used, that HTML first appears in light blue, and it changes to pink only after the JS runs.
So I made a small script that does nothing but put the saved color into a CSS variable, and loaded it in <head>. According to MDN's <script> page, a <script> with none of async, defer, or type="module" stops HTML parsing and runs immediately. Placed in <head>, the color is applied before the contents of <body> are read.
// A small script loaded in <head> before rendering. It puts the saved color into a CSS variable.
import { applyThemeColor, readStoredColor } from './theme';
applyThemeColor(readStoredColor());
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>サイトの色</title>
<link rel="stylesheet" href="/style.css">
<script src="/theme-init.js"></script>
</head>
I bundled this file separately from the React code with esbuild, in immediately invoked form (--format=iife). Since readStoredColor and applyThemeColor are shared with the React code, the logic for reading the color doesn't have to be written in two places. The bundled size was 623 bytes.
To check the effect, I saved pink, delayed only the loading of the React code by 1.5 seconds, and compared the screens 0.7 seconds after opening the page.

React だけで設定(サーバーで描いた HTML)
0.7秒後: --accent=#00c8e8 / header=rgb(0, 200, 232) / 選ばれているラジオボタン=水色
JS が届いたあと: --accent=#ea7896 / header=rgb(234, 120, 150) / 選ばれているラジオボタン=ピンク(開いてから 1.9 秒)
head で theme-init.js(サーバーで描いた HTML)
0.7秒後: --accent=#ea7896 / header=rgb(234, 120, 150) / 選ばれているラジオボタン=水色
JS が届いたあと: --accent=#ea7896 / header=rgb(234, 120, 150) / 選ばれているラジオボタン=ピンク(開いてから 1.8 秒)
(Some log lines are omitted.)
On the page that does not load theme-init.js, the page showed light blue until the JS arrived, then changed to pink. On the page that loads it, the page was pink from the start. On a page where React renders into an empty <div id="root"> rather than server-rendered HTML, the --accent value before the JS arrived split the same way: light blue without the script and pink with it.
However, even on the page that loads theme-init.js, the radio button still showed light blue as selected until the JS arrived. This is because, when rendering on the server, the HTML is built from the value returned by the third argument of useSyncExternalStore, getServerSnapshot (the default light blue). As React's official reference explains, this value is also used during hydration. In my test, after hydration the page was re-rendered with the getSnapshot value (the saved pink), and the radio button moved to pink. The development build also printed no React warnings. The division of labor is this: the color display is aligned early, and the selected state of the picker is aligned once the JS arrives.
Don't use the localStorage value as-is
A value in localStorage can be edited by the user in developer tools, or saved in a different form by an older version of the code. readStoredColor uses the value only when it has the #rrggbb form, and falls back to the default color otherwise. The results below are from my test, in which I edited the saved value and reloaded.
"red" → --accent #00c8e8 / 選ばれているラジオボタン 水色
"#12" → --accent #00c8e8 / 選ばれているラジオボタン 水色
"url(https://example.com/x.png)" → --accent #00c8e8 / 選ばれているラジオボタン 水色
"#EA7896" → --accent #ea7896 / 選ばれているラジオボタン ピンク
The uppercase #EA7896 is lowercased before comparing, so it matched the pink radio button.
Also, as MDN's localStorage page explains, when browser settings forbid a page from keeping data, even reading localStorage can throw a SecurityError. This is why readStoredColor and setThemeColor are wrapped in try. In my test, I made localStorage.setItem always throw. Even then, pressing purple changed the color, and the page showed no errors. Since nothing was saved, the color went back to the default light blue on reload.





