[ Getting started ]
Dark mode
Switch every component to dark with one class, persist the choice and avoid a flash on load.
Every component has dark styles built in. They switch on when an ancestor has the dark class or data-theme="dark". This is the same convention Tailwind uses, so one toggle controls both.
Add a theme toggle#
import { useEffect, useState } from 'react';
import { Switch } from 'reusify-ui';
export function ThemeToggle() {
const [dark, setDark] = useState(
() => localStorage.getItem('theme') === 'dark' ||
(!localStorage.getItem('theme') && matchMedia('(prefers-color-scheme: dark)').matches),
);
useEffect(() => {
document.documentElement.classList.toggle('dark', dark);
localStorage.setItem('theme', dark ? 'dark' : 'light');
}, [dark]);
return <Switch label="Dark mode" checked={dark} onChange={setDark} />;
}Avoid a flash on load#
Apply the saved theme before React renders by putting a tiny inline script in the <head> of index.html:
index.html
<script>
const saved = localStorage.getItem('theme');
const dark = saved ? saved === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
if (dark) document.documentElement.classList.add('dark');
</script>Dark sections#
Because the switch is just a class, you can render one area dark inside a light page:
Light card
Inherits the page theme.
Always dark
className="dark" on the wrapper.
<div className="dark" style={{ background: 'var(--ru-bg)' }}>
<Alert variant="success" title="Always dark">…</Alert>
</div>Customizing the dark palette
Override variables under.dark the same way you do under :root. See Theming for the full token list with light and dark values.