← Components

Utilities

Theme toggle

Switches light and dark. The new theme blooms out from the button as a growing circle; the icon flips. Remembers the choice.

Examples and variants

Bloom

Press it (Chromium and Safari show the bloom).

The new theme blooms out from the button.

Example
function ThemeBloom() {
  return (
    <div className="flex flex-col items-center gap-3">
      <ThemeToggle className="size-(--size-control-lg) shadow-1 [&_svg]:size-(--size-icon-lg)" />
      <p className="text-sm text-muted-foreground">The new theme blooms out from the button.</p>
    </div>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/theme-toggle.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install cn lucide-react
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/theme-toggle.tsxtheme-toggle
      components/ui/theme-toggle.tsx
      "use client"
      
      import * as React from "react"
      import { MoonIcon, SunIcon } from "lucide-react"
      import { cn } from "cn"
      import { motionLevel } from "@/lib/overlay"
      
      /*
        Theme toggle: switches light and dark. The new theme blooms out from the
        button as a growing circle (View Transitions); the icon flips sun ↔ moon.
        Calm crossfades; still and reduced motion switch instantly; browsers
        without View Transitions switch instantly too.
      */
      type Mode = "light" | "dark"
      
      function readMode(): Mode {
        if (typeof document === "undefined") return "light"
        return document.documentElement.classList.contains("dark") ? "dark" : "light"
      }
      
      function subscribe(onChange: () => void) {
        const observer = new MutationObserver(onChange)
        observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] })
        return () => observer.disconnect()
      }
      
      function applyMode(mode: Mode, storageKey: string) {
        document.documentElement.classList.toggle("dark", mode === "dark")
        try {
          window.localStorage.setItem(storageKey, mode)
        } catch {
          /* storage can be blocked; the class still applies */
        }
      }
      
      function ThemeToggle({ storageKey = "isotope-mode", className }: { storageKey?: string; className?: string }) {
        const mode = React.useSyncExternalStore(subscribe, readMode, (): Mode => "light")
        const ref = React.useRef<HTMLButtonElement>(null)
      
        React.useEffect(() => {
          let stored: string | null = null
          try {
            stored = window.localStorage.getItem(storageKey)
          } catch {
            stored = null
          }
          const preferred: Mode =
            stored === "light" || stored === "dark" ? stored : window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
          applyMode(preferred, storageKey)
        }, [storageKey])
      
        function toggle() {
          const next: Mode = readMode() === "dark" ? "light" : "dark"
          const button = ref.current
          const level = motionLevel(button)
          const doc = document as Document & { startViewTransition?: (cb: () => void) => unknown }
          if (!doc.startViewTransition || level === "still" || !button) {
            applyMode(next, storageKey)
            return
          }
          const box = button.getBoundingClientRect()
          const x = box.left + box.width / 2
          const y = box.top + box.height / 2
          const r = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))
          const root = document.documentElement
          root.style.setProperty("--bloom-x", `${x}px`)
          root.style.setProperty("--bloom-y", `${y}px`)
          root.style.setProperty("--bloom-r", `${r}px`)
          root.dataset.bloom = level === "calm" ? "fade" : "circle"
          const transition = doc.startViewTransition(() => applyMode(next, storageKey)) as { finished?: Promise<void> }
          transition.finished?.finally(() => delete root.dataset.bloom)
        }
      
        return (
          <button
            ref={ref}
            type="button"
            data-slot="theme-toggle"
            onClick={toggle}
            aria-label={mode === "dark" ? "Switch to light mode" : "Switch to dark mode"}
            className={cn(
              "liquid-press inline-flex size-(--size-control-sm) items-center justify-center rounded-(--shape-full) text-foreground outline-none hover:bg-(--theme-toggle-container-hover) active:bg-(--theme-toggle-container-pressed) focus-visible:shadow-(--focus-ring) [&_svg]:size-(--size-icon-sm)",
              className
            )}
          >
            <span key={mode} className="theme-flip inline-flex">
              {mode === "dark" ? <SunIcon aria-hidden /> : <MoonIcon aria-hidden />}
            </span>
          </button>
        )
      }
      
      export { ThemeToggle }
      

Imports

What the examples on this page import:

Imports
import { Bubble, BubbleReactions } from "@/components/ui/bubble"
import { PickerWheel } from "@/components/ui/picker-wheel"
import { ReactionPicker } from "@/components/ui/reaction-picker"
import { RollingNumber } from "@/components/ui/rolling-number"
import { Slider } from "@/components/ui/slider"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ThemeToggle } from "@/components/ui/theme-toggle"

Anatomy

  1. 1Button · Icon button; sun or moon.
  2. 2Bloom · View transition clip circle from the button.

Props

PropTypeDefaultDescription
storageKeystring"isotope-mode"Where the choice is saved.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

This utility has no component tokens; it uses semantic tokens directly.

TokenPoints toLightDark

Motion

TriggerWhat happensTokens
SwitchCircle grows from the button over the old theme; calm crossfades.--duration-settle

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • The label says what it will switch to.
  • Still and reduced motion switch instantly.

Usage

Do

  • Put it in the header.

Don’t

  • Don't hide it in a menu if people switch often.

Code

components/ui/theme-toggle.tsx
"use client"

import * as React from "react"
import { MoonIcon, SunIcon } from "lucide-react"
import { cn } from "cn"
import { motionLevel } from "@/lib/overlay"

/*
  Theme toggle: switches light and dark. The new theme blooms out from the
  button as a growing circle (View Transitions); the icon flips sun ↔ moon.
  Calm crossfades; still and reduced motion switch instantly; browsers
  without View Transitions switch instantly too.
*/
type Mode = "light" | "dark"

function readMode(): Mode {
  if (typeof document === "undefined") return "light"
  return document.documentElement.classList.contains("dark") ? "dark" : "light"
}

function subscribe(onChange: () => void) {
  const observer = new MutationObserver(onChange)
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] })
  return () => observer.disconnect()
}

function applyMode(mode: Mode, storageKey: string) {
  document.documentElement.classList.toggle("dark", mode === "dark")
  try {
    window.localStorage.setItem(storageKey, mode)
  } catch {
    /* storage can be blocked; the class still applies */
  }
}

function ThemeToggle({ storageKey = "isotope-mode", className }: { storageKey?: string; className?: string }) {
  const mode = React.useSyncExternalStore(subscribe, readMode, (): Mode => "light")
  const ref = React.useRef<HTMLButtonElement>(null)

  React.useEffect(() => {
    let stored: string | null = null
    try {
      stored = window.localStorage.getItem(storageKey)
    } catch {
      stored = null
    }
    const preferred: Mode =
      stored === "light" || stored === "dark" ? stored : window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
    applyMode(preferred, storageKey)
  }, [storageKey])

  function toggle() {
    const next: Mode = readMode() === "dark" ? "light" : "dark"
    const button = ref.current
    const level = motionLevel(button)
    const doc = document as Document & { startViewTransition?: (cb: () => void) => unknown }
    if (!doc.startViewTransition || level === "still" || !button) {
      applyMode(next, storageKey)
      return
    }
    const box = button.getBoundingClientRect()
    const x = box.left + box.width / 2
    const y = box.top + box.height / 2
    const r = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))
    const root = document.documentElement
    root.style.setProperty("--bloom-x", `${x}px`)
    root.style.setProperty("--bloom-y", `${y}px`)
    root.style.setProperty("--bloom-r", `${r}px`)
    root.dataset.bloom = level === "calm" ? "fade" : "circle"
    const transition = doc.startViewTransition(() => applyMode(next, storageKey)) as { finished?: Promise<void> }
    transition.finished?.finally(() => delete root.dataset.bloom)
  }

  return (
    <button
      ref={ref}
      type="button"
      data-slot="theme-toggle"
      onClick={toggle}
      aria-label={mode === "dark" ? "Switch to light mode" : "Switch to dark mode"}
      className={cn(
        "liquid-press inline-flex size-(--size-control-sm) items-center justify-center rounded-(--shape-full) text-foreground outline-none hover:bg-(--theme-toggle-container-hover) active:bg-(--theme-toggle-container-pressed) focus-visible:shadow-(--focus-ring) [&_svg]:size-(--size-icon-sm)",
        className
      )}
    >
      <span key={mode} className="theme-flip inline-flex">
        {mode === "dark" ? <SunIcon aria-hidden /> : <MoonIcon aria-hidden />}
      </span>
    </button>
  )
}

export { ThemeToggle }