Skip to content

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-theme on 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.

ThemeToggle props
PropTypeDefaultDescription
classNamestring—Extra classes, for spacing.

Tokens

Tokens
TokenDefaultSets
--toggle-size2.25remWidth and height
--toggle-radius--radius-controlCorner radius
--toggle-backgroundtransparentFill
--toggle-border--borderBorder colour
--toggle-text--foregroundPicture colour