Skip to content
Thrum

Theme switcher

A control for the colour theme: light, dark, or whatever the system prefers. It reports the choice and shows it; the app applies it, so it fits a class, a data attribute or any other setup. For a plain on and off setting use a switch.

Install

npx shadcn@latest add https://thrumui.dev/r/theme-switcher.json

Adds components/ui/theme-switcher.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.

import { ThemeSwitcher } from "@/components/ui/theme-switcher";

Automatically installs icons check, monitor, moon and sun from the icon set.

Props

PropTypeDefaultDescription
value"light" | "dark" | "system"–The chosen theme, when the parent holds it. Use it with onValueChange.
defaultValue"light" | "dark" | "system"Default "system"The theme chosen at first, when the switcher holds it itself.
onValueChange(value: Theme) => void–Called with the new choice. Apply it to the page here: the switcher never reads or writes the document.
variant"segmented" | "toggle" | "menu"Default "segmented"segmented shows the three choices in a row. toggle is one button that flips between light and dark. menu is a button that opens a list of the three.
systemTheme"light" | "dark"Default "light"What system resolves to now. The toggle and the menu button show its glyph while the choice is system, and the toggle flips away from it.
labelsbooleanDefault falsePrint the names next to the glyphs. Without them each button is named for screen readers only.
size"sm" | "md" | "lg"Default "md"28, 32 or 40 pixels tall.
disabledbooleanDefault falseDimmed, and it cannot be changed.
soundbooleanDefault truePlay a click when the theme changes, and the open and close sounds of the menu, if the visitor has sound on.
classNamestring–Classes for the root element.

Motion and sound

Motion

  • A newly chosen button takes its pressed colours over 150 ms.
  • The menu fades in and grows from 96% to full size over 150 ms, from the edge that touches the button, and plays it backwards to close.
  • Reduced motion: every change is immediate.

Sound

  • A click when the theme changes. Pressing the theme that is already chosen makes no sound.
  • In the menu variant, a soft rising tone when the list opens and a falling one when it closes without a pick.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • Segmented is a group named Theme of three toggle buttons; the chosen one is pressed and filled, so the choice never rests on colour alone.
  • Toggle is one button named Dark theme with aria-pressed: pressed means dark. Its glyph changes too.
  • Menu follows the WAI-ARIA menu button pattern: a button named Theme with the current choice, opening a menu of three radio items. The chosen one carries a tick.
  • Without labels the buttons are named Light, Dark and System for screen readers. With labels the names are printed.
  • Under a glass material the menu is translucent. Its tint keeps the text at 4.5 to 1 over any page.
  • The demo does not change this site's theme: the site's colours are set on the page root only, so the demo prints the choice instead.
KeysAction
TabSegmented: reach the row as one stop. Toggle and menu: reach the button.
← / →Segmented: move between the three buttons.
Enter / SpaceChoose the focused theme, flip the toggle, or open the menu.
↓ / ↑Menu: open it, then move between the three themes.
EnterMenu: choose the highlighted theme and close the list. Focus returns to the button.
EscMenu: close the list without a change.

Source

components/ui/theme-switcher.tsx
"use client";

import { useState } from "react";
import { Menu as MenuPrimitive } from "@base-ui/react/menu";

import { cn } from "@/lib/utils";
import { CheckIcon } from "@/components/icons/check";
import { MonitorIcon } from "@/components/icons/monitor";
import { MoonIcon } from "@/components/icons/moon";
import { SunIcon } from "@/components/icons/sun";
import { play } from "@/lib/thrum-sound";
import { buttonClass } from "@/components/ui/button";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

export type Theme = "light" | "dark" | "system";
export type ThemeSwitcherVariant = "segmented" | "toggle" | "menu";
export type ThemeSwitcherSize = "sm" | "md" | "lg";

export type ThemeSwitcherProps = {
  /** The chosen theme, when the parent holds it. Use it with `onValueChange`. */
  value?: Theme;
  /** The theme chosen at first, when the switcher holds it itself. */
  defaultValue?: Theme;
  /** Called with the new choice. Apply it to the page here: the switcher never touches the document. */
  onValueChange?: (value: Theme) => void;
  /** `segmented` shows the three choices in a row, `toggle` is one button that flips light and dark, `menu` is a button that opens a list. */
  variant?: ThemeSwitcherVariant;
  /** What "system" resolves to now, from `prefers-color-scheme`. The toggle shows it and flips away from it. */
  systemTheme?: "light" | "dark";
  /** Print the names next to the glyphs. Without them the buttons are named for screen readers only. */
  labels?: boolean;
  /** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
  size?: ThemeSwitcherSize;
  /** Dimmed, and it cannot be changed. */
  disabled?: boolean;
  /** Play a click when the theme changes, and the list's open and close sounds, if the visitor has sound on. */
  sound?: boolean;
  /** Classes for the root element. */
  className?: string;
};

const NAMES: Record<Theme, string> = { light: "Light", dark: "Dark", system: "System" };
const GLYPH: Record<Theme, typeof SunIcon> = { light: SunIcon, dark: MoonIcon, system: MonitorIcon };
const THEMES: readonly Theme[] = ["light", "dark", "system"];

/**
 * A control for the colour theme: light, dark, or the system's choice. It only reports and reflects a value:
 * applying it to the page is up to the app, so it works with any theme setup. Its name is "Theme".
 */
export function ThemeSwitcher({
  value,
  defaultValue = "system",
  onValueChange,
  variant = "segmented",
  systemTheme = "light",
  labels = false,
  size = "md",
  disabled = false,
  sound = true,
  className,
}: ThemeSwitcherProps) {
  const [own, setOwn] = useState<Theme>(defaultValue);
  const theme = value ?? own;
  const shown = theme === "system" ? systemTheme : theme;

  const choose = (next: Theme) => {
    if (next === theme) return;
    if (sound) play("select");
    setOwn(next);
    onValueChange?.(next);
  };

  if (variant === "toggle") {
    const Glyph = GLYPH[shown];
    const dark = shown === "dark";
    return (
      // One two-state button: pressed means dark. A press always makes an explicit choice, so "system" ends here.
      <button
        type="button"
        data-slot="theme-switcher"
        data-theme-value={theme}
        aria-label={labels ? undefined : "Dark theme"}
        aria-pressed={dark}
        disabled={disabled}
        onClick={() => choose(dark ? "light" : "dark")}
        className={cn(buttonClass({ variant: "outline", size: labels ? size : "icon" }), !labels && ICON_SIZE[size], "[&_svg]:size-4", className)}
      >
        <Glyph />
        {labels && <span>{dark ? "Dark theme" : "Light theme"}</span>}
      </button>
    );
  }

  if (variant === "menu") {
    const Glyph = GLYPH[shown];
    return (
      <MenuPrimitive.Root
        disabled={disabled}
        onOpenChange={(open, details) => {
          // A pick closes the list and makes its own sound.
          if (sound && details.reason !== "item-press") play(open ? "open" : "close");
        }}
      >
        <MenuPrimitive.Trigger
          data-slot="theme-switcher"
          data-theme-value={theme}
          aria-label={labels ? undefined : `Theme: ${NAMES[theme]}`}
          className={cn(buttonClass({ variant: "outline", size: labels ? size : "icon" }), !labels && ICON_SIZE[size], "[&_svg]:size-4", className)}
        >
          <Glyph />
          {labels && <span>{NAMES[theme]}</span>}
        </MenuPrimitive.Trigger>
        <MenuPrimitive.Portal>
          <MenuPrimitive.Positioner sideOffset={4} align="end" collisionPadding={8} className="z-50 outline-none">
            <MenuPrimitive.Popup
              data-slot="theme-switcher-menu"
              data-surface="floating"
              className={cn(
                "min-w-36 origin-(--transform-origin) rounded-lg border bg-popover p-2 text-popover-foreground shadow-md outline-none",
                "transition-[opacity,scale] duration-150 ease-out data-ending-style:scale-[0.96] data-ending-style:opacity-0 data-starting-style:scale-[0.96] data-starting-style:opacity-0 motion-reduce:transition-none",
              )}
            >
              <MenuPrimitive.RadioGroup value={theme} onValueChange={(next: Theme) => choose(next)}>
                {THEMES.map((option) => {
                  const OptionGlyph = GLYPH[option];
                  return (
                    <MenuPrimitive.RadioItem
                      key={option}
                      value={option}
                      closeOnClick
                      className="grid min-h-8 cursor-default grid-cols-[1rem_1fr_1rem] items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground [&_svg]:size-4"
                    >
                      <OptionGlyph className="text-muted-foreground" />
                      {NAMES[option]}
                      {/* The tick marks the chosen theme, so the choice never rests on the highlight colour. */}
                      <MenuPrimitive.RadioItemIndicator>
                        <CheckIcon />
                      </MenuPrimitive.RadioItemIndicator>
                    </MenuPrimitive.RadioItem>
                  );
                })}
              </MenuPrimitive.RadioGroup>
            </MenuPrimitive.Popup>
          </MenuPrimitive.Positioner>
        </MenuPrimitive.Portal>
      </MenuPrimitive.Root>
    );
  }

  return (
    <ToggleGroup
      data-slot="theme-switcher"
      data-theme-value={theme}
      aria-label="Theme"
      variant="outline"
      size={size}
      sound={false}
      disabled={disabled}
      value={[theme]}
      // Pressing the chosen item again would leave nothing chosen. One theme is always on.
      onValueChange={(next) => next[0] && choose(next[0] as Theme)}
      className={className}
    >
      {THEMES.map((option) => {
        const OptionGlyph = GLYPH[option];
        return (
          <ToggleGroupItem key={option} value={option} aria-label={labels ? undefined : NAMES[option]}>
            <OptionGlyph />
            {labels && NAMES[option]}
          </ToggleGroupItem>
        );
      })}
    </ToggleGroup>
  );
}

const ICON_SIZE: Record<ThemeSwitcherSize, string> = { sm: "size-7", md: "size-8", lg: "size-10" };

Files and dependencies

Adds
components/ui/theme-switcher.tsx
Packages
@base-ui/react@1.9.0
Brings along
Sound engineButtonToggle group
Icons
checkmonitormoonsun

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor