ThemeToggle
Switches between light and dark colours. Every site has one.
import { ThemeToggle } from '@/design-system';Examples
import { ThemeToggle } from '@/design-system';
export default function ThemeToggleBasic() {
return <ThemeToggle />;
}Setting up
Declare both colour schemes in the site’s CSS, and give each colour a light and a dark value:
:root {
color-scheme: light dark;
--background: light-dark(#fafafa, #121214);
}
:root[data-theme='light'] {
color-scheme: light;
}
:root[data-theme='dark'] {
color-scheme: dark;
}Then run themeScript in the head, so a saved choice is applied before the page is drawn:
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
…How it works
- Until the visitor chooses, the colours follow the device and change with it.
- A choice sets
data-themeon the page and is saved in the browser, including for other open tabs. Choosing what the device already uses goes back to following the device. - It is a button named “Dark mode” with
aria-pressed. - For a control of your own,
useColorScheme()gives the scheme shown and a function that changes it.
Props
ThemeToggle takes only this prop.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | — | Extra classes, for spacing. |
Tokens
| Token | Default | Sets |
|---|---|---|
--toggle-size | 2.25rem | Width and height |
--toggle-radius | --radius-control | Corner radius |
--toggle-background | transparent | Fill |
--toggle-border | --border | Border colour |
--toggle-text | --foreground | Picture colour |