Skip to content

Components

ThemeToggle

jsx
import React from "react";
import { ThemeToggle } from "cherry-styled-components";

export default function Page() {
  return <ThemeToggle />;
}

The ThemeToggle is a pill-shaped switch for light and dark mode. It shows a sun and a moon side by side, with a soft circular highlight over the active icon. The highlight jumps to the other icon when the mode changes: Cherry turns transitions off for the frame that paints a mode switch, so the whole page changes at once.

ThemeToggle works with the providers described on the Dark Mode page.

It works out of the box inside CherryThemeProvider or ClientThemeProvider: clicking it calls toggleTheme() from ThemeContext, which switches to the other mode, stores it as the visitor's choice (themePreference in localStorage), mirrors the mode to the theme cookie, and flips the dark class on the <html> element. No styled component renders again, and no wiring is needed. The highlight's position comes from that dark class, so with themeInitScript in the document head it starts in the right place on the first paint. See Dark Mode for the flash-free SSR setup, and for setPreference to offer a "system" option.

Keep in mind that the <button> element inherently includes native browser properties like onClick. Cherry UI components introduce custom properties that always begin with a $ to distinguish them from native props.

A custom onClick runs after the mode switch, which is handy for analytics:

html
<ThemeToggle onClick={() => trackEvent("theme toggled")} />

Hide it with the $hidden prop, for example on a page that pins a mode with $mode:

html
<ThemeToggle $hidden={isPinned} />

Keyboard Shortcut

Bind the Command + Shift + L (Ctrl + Shift + L on Windows) shortcut with the $shortcut prop. While the toggle is mounted, pressing it flips the mode without a click:

html
<ThemeToggle $shortcut />

The shortcut listens on window, is removed when the toggle unmounts, and calls the same toggleTheme as a click, so the choice is persisted the same way. It requires Shift and ignores Alt so it stays clear of the browser's Cmd/Ctrl+L address-bar shortcut. Like clicking, it does nothing until a themeDark is passed to the provider, or while the provider pins a mode with $mode.

ThemeToggle requires a themeDark to be passed to the theme provider. Without it there is nothing to switch to, and clicking the button does nothing. The same goes while the provider pins a mode with $mode.

Properties

$hiddenboolean

Hides the toggle with display: none, for example on a page whose mode is pinned.

$shortcutboolean

Binds the Command + Shift + L (Ctrl + Shift + L on Windows) keyboard shortcut while the toggle is mounted, flipping the mode without a click. Off by default.