Actions
Theme toggle
Switches the page from the light to the dark theme in one click, with an animated transition.
Example
A round button whose sun turns into a moon: its rays tuck in and a disc slides over it to carve the crescent. A click sets data-theme="dark" (or "light") on <html>, which turns on the dark theme of the whole page, then emits crChange with the new theme. Try it: it changes the theme of this whole documentation.
@lea.simon
Appearance Light ›
'use client';
import { useState, useSyncExternalStore } from 'react';
import { CrAvatar, CrBox, CrSegmented, CrSwitch, CrThemeToggle } from '@cristal-ui/react';
const transitions = [
['circle', 'Circle'],
['curtain', 'Curtain'],
['blinds', 'Blinds'],
['flip', 'Flip'],
['eclipse', 'Eclipse'],
['sweep', 'Sweep'],
] as const;
// The displayed theme, read again on every change of data-theme on <html>, wherever it comes from.
const subscribe = (update: () => void) => {
const observer = new MutationObserver(update);
observer.observe(document.documentElement, { attributeFilter: ['data-theme'] });
return () => observer.disconnect();
};
const pageTheme = () => document.documentElement.dataset.theme;
export default function ThemeToggleProfile() {
const [index, setIndex] = useState(0);
const theme = useSyncExternalStore(subscribe, pageTheme, () => undefined);
return (
<CrBox display="flex" direction="column" gap="lg" align="stretch">
<CrSegmented label="Transition" value={String(index)} onCrChange={(event) => setIndex(Number(event.detail))}>
{transitions.map(([transition, label], value) => (
<option key={transition} value={value}>
{label}
</option>
))}
</CrSegmented>
<section aria-label="Profile" style={{ position: 'relative', width: '100%', maxWidth: 360, margin: '0 auto', padding: 24, boxSizing: 'border-box', background: 'var(--cr-color-surface)', border: '1px solid var(--cr-color-border)', borderRadius: 'var(--cr-radius-l)' }}>
<CrThemeToggle transition={transitions[index][0]} style={{ position: 'absolute', top: 16, right: 16 }} />
<CrBox display="flex" direction="column" gap="lg">
<CrBox display="flex" gap="lg" align="center">
<CrAvatar name="Léa Simon" size="l" />
<div>
<strong>Léa Simon</strong>
<p style={{ margin: 0, color: 'var(--cr-color-text-muted)' }}>@lea.simon</p>
</div>
</CrBox>
<p style={{ display: 'flex', justifyContent: 'space-between', margin: 0 }}>
Appearance <span style={{ color: 'var(--cr-color-text-muted)' }}>{theme === 'dark' ? 'Dark' : 'Light'} ›</span>
</p>
<CrSwitch label="Notifications" checked />
</CrBox>
</section>
</CrBox>
);
}The dark theme comes from @cristal-ui/react/tokens-dark.css: import it after tokens.css, otherwise the toggle changes the attribute while the components keep their colours.
Variants
variant chooses the shape of the toggle:
icon(default): a round button, no text;switch: a real switch; the thumb slides carrying the sun or the moon, and the track goes from day (light, a soft sun glow) to night (dark, a few stars);label: a pill button, with the icon and the visible label "Dark theme".
'use client';
import { CrBox, CrThemeToggle } from '@cristal-ui/react';
export default function ThemeToggleVariants() {
return (
<CrBox display="flex" gap="xl" align="center" justify="center" wrap>
<CrThemeToggle variant="icon" />
<CrThemeToggle variant="switch" />
<CrThemeToggle variant="label" />
</CrBox>
);
}icon and label are toggle buttons (aria-pressed): "Dark theme, toggle button, pressed". switch is a switch (role="switch" and aria-checked): "Dark theme, switch, on". Same name, same effect; only the way it is announced changes, to match what the user sees.
Icon animation
icon chooses how the sun and the moon animate, in all three variants (inside the thumb for switch):
morph(default): the rays tuck in and a disc carves the crescent;rotate: the sun spins out and shrinks, the moon spins in;rise: the sun sets below a horizon line, then the moon rises;flip: a coin flipping in 3D, the sun on one face, the moon on the other;eclipse: a disc slides across the sun, its rays fade out and stars light up.
'use client';
import { useState } from 'react';
import { CrBox, CrSegmented, CrThemeToggle } from '@cristal-ui/react';
const icons = [
['morph', 'Morph'],
['rotate', 'Rotation'],
['rise', 'Horizon'],
['flip', 'Coin'],
['eclipse', 'Eclipse'],
] as const;
export default function ThemeToggleIcons() {
const [index, setIndex] = useState(0);
const icon = icons[index][0];
return (
<CrBox display="flex" direction="column" gap="xl" align="center">
<CrSegmented label="Icon animation" value={String(index)} onCrChange={(event) => setIndex(Number(event.detail))}>
{icons.map(([value, label], position) => (
<option key={value} value={position}>
{label}
</option>
))}
</CrSegmented>
<CrBox display="flex" gap="xl" align="center" justify="center" wrap>
<CrThemeToggle variant="icon" icon={icon} />
<CrThemeToggle variant="switch" icon={icon} />
<CrThemeToggle variant="label" icon={icon} />
</CrBox>
</CrBox>
);
}Transitions
transition chooses how the new theme replaces the old one, over the whole page, whatever the variant (circle and eclipse start from the centre of the button, or of the switch thumb):
circle(default): a circle growing from the button;curtain: the new theme drops from the top like a curtain;blinds: horizontal bands switch one after another, top to bottom;flip: the page flips in 3D, its back is the other theme;eclipse: a huge soft-edged disc glides across the screen;sweep: the new theme sweeps the screen like a clock hand;none: instant change.
Transitions use the View Transitions API. Where it is missing, and always when the user asked for reduced motion, the theme changes at once, with no transition and no icon animation.
Initial theme and outside changes
On load, the toggle takes the theme from data-theme on <html>, otherwise the system preference. It then follows every change of data-theme, wherever it comes from: to change the theme from your application, set the attribute and the toggle updates.
This documentation uses that with next-themes: it sets data-theme in addition to the dark class, and on crChange it hands the choice to next-themes (setTheme), which keeps it. The toggle and the documentation's theme switcher therefore stay in agreement, both ways.
Keeping the choice
The toggle remembers nothing: keeping the choice is up to the application, for example in localStorage.
<CrThemeToggle onCrChange={(event) => localStorage.setItem('theme', event.detail)} />To avoid a flash of the wrong theme on reload, set the attribute before the first paint, with an inline script in <head>. suppressHydrationWarning on <html> avoids React's warning for this attribute added before hydration.
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: "const t = localStorage.getItem('theme'); if (t) document.documentElement.dataset.theme = t;" }} />
</head>
<body>{children}</body>
</html>Accessibility
- A real
<button>witharia-pressed: announced "Dark theme, toggle button, pressed / not pressed", activated by click, Enter or Space. The name follows the page language. switch: the same<button>withrole="switch"andaria-checked, activated by click, Space or Enter; a 60 × 32 px target. The thumb keeps 3:1 or more against its track, and the track edge 3:1 or more against the page, in both themes. In high contrast mode, track and thumb take the system colours; the state also shows through the thumb position and the icon, not colour alone.label: the visible label "Dark theme" never changes and is the whole accessible name (the name always contains the visible text, "label in name"); the state goes througharia-pressedand the icon.- The icon is decorative (
aria-hidden); the state is given byaria-pressed, not only by the sun or the moon. - A 40 × 40 px target, a visible focus outline, and an icon and border at 3:1 or more in both themes; in high contrast mode, icon, border and focus take the system colours.
- Transitions never fade text in from zero opacity: only shapes (circle, bands, disc, hand) uncover the new theme, already readable.
- When reduced motion is requested, no transition, no icon animation and no thumb slide: the theme, the icon and the switch change at once.
API
Properties
| Property | Type | Default | Description |
|---|---|---|---|
icon | "eclipse" | "flip" | "morph" | "rise" | "rotate" | 'morph' | Animation de l'icône : morph (le soleil devient une lune, par défaut), rotate (le soleil tourne et rapetisse, la lune arrive en tournant), rise (le soleil se couche sous l'horizon, la lune se lève), flip (pièce qui se retourne) ou eclipse (un disque passe devant le soleil, les rayons deviennent des étoiles). |
theme | "dark" | "light" | 'light' | Thème affiché ; au chargement, celui de data-theme sur <html>, sinon la préférence du système. Pour en changer depuis l'application, posez data-theme sur <html> : la bascule suit. |
transition | "blinds" | "circle" | "curtain" | "eclipse" | "flip" | "none" | "sweep" | 'circle' | Passage d'un thème à l'autre : circle (cercle depuis le bouton, par défaut), curtain (rideau qui tombe), blinds (bandes de haut en bas), flip (la page se retourne), eclipse (disque qui glisse), sweep (aiguille d'horloge) ou none. Instantané si l'utilisateur réduit les animations ou si le navigateur ne connaît pas les transitions de vue. |
variant | "icon" | "label" | "switch" | 'icon' | Forme de la bascule : icon (bouton rond, par défaut), switch (interrupteur dont la pastille glisse, rôle switch) ou label (bouton avec l'icône et le libellé « Thème sombre » visible). |
Events
| React | event.detail | Description |
|---|---|---|
onCrChange | "dark" | "light" | Émis après chaque changement de thème par la bascule, une fois data-theme posé ; detail : le nouveau thème. |
CSS parts
To style it from outside: cr-theme-toggle::part(name) { … }
| Part | Description |
|---|---|
button | Le bouton natif (le rail pour l'interrupteur). |
icon | L'icône soleil / lune. |
thumb | La pastille de l'interrupteur, qui porte l'icône. |