Theme Toggle
An animated dark mode toggle for React and Tailwind CSS: the icon morphs from a sun into a moon and the new theme is revealed with a circle that grows out of the button, using the View Transitions API. It works with any theme setup (next-themes, a class on <html>, or a single panel) and falls back to an instant switch.
- View Transitions API
- Sun ↔ moon morph
- Works with next-themes
- Scoped to any element
- prefers-reduced-motion
Last 7 days
Visitors
24.8k
+12%
Signups
1,204
+8%
"use client";
import * as React from "react";
import { Bell, TrendingUp } from "lucide-react";
import { ThemeToggle } from "@/components/dusk/theme-toggle/theme-toggle";
// The docs site is dark-only, so this preview carries its own light and dark
// palette as CSS variables and only this panel is switched.
const palette = [
"[--pv-bg:#ffffff] [--pv-fg:#0a0a0a] [--pv-muted:#71717a] [--pv-card:#f4f4f5] [--pv-border:#e4e4e7] [--pv-accent:#059669]",
"[&.dark]:[--pv-bg:#0a0a0a] [&.dark]:[--pv-fg:#f4f4f5] [&.dark]:[--pv-muted:#a1a1aa] [&.dark]:[--pv-card:#18181b] [&.dark]:[--pv-border:#27272a] [&.dark]:[--pv-accent:var(--color-primary)]",
].join(" ");
const stats = [
{ label: "Visitors", value: "24.8k", change: "+12%" },
{ label: "Signups", value: "1,204", change: "+8%" },
];
export default function ThemeToggleDemo() {
const preview = React.useRef<HTMLDivElement>(null);
return (
<div
ref={preview}
// Starts dark to match the toggle's default theme, so there is no flash on load.
className={`dark ${palette} w-full max-w-sm overflow-hidden rounded-xl border border-(--pv-border) bg-(--pv-bg) text-(--pv-fg) shadow-lg`}
>
<header className="flex items-center justify-between border-b border-(--pv-border) px-5 py-3">
<span className="font-semibold tracking-tight">Acme Analytics</span>
<div className="flex items-center gap-1">
<span className="grid size-9 place-items-center rounded-full text-(--pv-muted)">
<Bell className="size-[18px]" aria-hidden />
</span>
<ThemeToggle target={preview} />
</div>
</header>
<div className="space-y-4 p-5">
<p className="text-sm text-(--pv-muted)">Last 7 days</p>
<div className="grid grid-cols-2 gap-3">
{stats.map((stat) => (
<div key={stat.label} className="rounded-xl bg-(--pv-card) p-4">
<p className="text-xs text-(--pv-muted)">{stat.label}</p>
<p className="mt-1 text-2xl font-semibold tabular-nums">{stat.value}</p>
<p className="mt-1 inline-flex items-center gap-1 text-xs font-medium text-(--pv-accent)">
<TrendingUp className="size-3.5" aria-hidden />
{stat.change}
</p>
</div>
))}
</div>
<div className="flex h-20 items-end gap-1.5 rounded-xl bg-(--pv-card) p-3" aria-hidden>
{[40, 65, 50, 80, 60, 95, 75].map((h, i) => (
<span key={i} className="flex-1 rounded-sm bg-(--pv-muted)" style={{ height: `${h}%`, opacity: 0.5 }} />
))}
</div>
</div>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/theme-toggle.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/theme-toggle/theme-toggle.tsx.theme-toggle.tsx "use client"; import * as React from "react"; import { flushSync } from "react-dom"; import { motion, useReducedMotion, type Transition } from "motion/react"; import { cn } from "@/lib/utils"; export type Theme = "light" | "dark"; /** Element whose class is switched: a ref, the element itself, or a getter. */ export type ThemeTarget = | React.RefObject<HTMLElement | null> | HTMLElement | null | (() => HTMLElement | null); export interface ThemeToggleProps extends Omit<React.ComponentProps<"button">, "onClick" | "children" | "type"> { /** Current theme (controlled). Pair with `onThemeChange`. */ theme?: Theme; /** Initial theme when uncontrolled. */ defaultTheme?: Theme; /** Called with the next theme, inside the view transition so the new snapshot shows it. */ onThemeChange?: (theme: Theme) => void; /** Element that gets the `darkClass`. Defaults to `document.documentElement`. */ target?: ThemeTarget; /** Toggle `darkClass` and `color-scheme` on the target. Turn off when a theme library (next-themes) does it. */ applyClass?: boolean; /** Class added to the target in dark mode. */ darkClass?: string; /** `"circle"` reveals the new theme from the button; `"none"` switches instantly. */ transition?: "circle" | "none"; /** Reveal duration in milliseconds. */ duration?: number; /** CSS easing for the reveal. */ easing?: string; size?: "sm" | "default" | "lg"; variant?: "outline" | "ghost"; /** Accessible name. The pressed state says whether dark mode is on. */ label?: string; } const morph: Transition = { type: "spring", bounce: 0.1, duration: 0.5 }; const sizes = { sm: "size-8 [&_svg]:size-4", default: "size-9 [&_svg]:size-[18px]", lg: "size-11 [&_svg]:size-[22px]", } as const; const variants = { outline: "border border-current/15 bg-current/[0.04] hover:bg-current/[0.08]", ghost: "hover:bg-current/[0.08]", } as const; // Ray endpoints, precomputed so server and client markup are identical. const rays = [ [12, 3.2, 12, 1.4], [18.22, 5.78, 19.5, 4.5], [20.8, 12, 22.6, 12], [18.22, 18.22, 19.5, 19.5], [12, 20.8, 12, 22.6], [5.78, 18.22, 4.5, 19.5], [3.2, 12, 1.4, 12], [5.78, 5.78, 4.5, 4.5], ] as const; /** One SVG that morphs a sun into a crescent moon with two twinkling stars. */ function SunMoonGlyph({ dark }: { dark: boolean }) { const maskId = `theme-toggle-${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; return ( <motion.svg viewBox="0 0 24 24" fill="none" aria-hidden initial={false} animate={{ rotate: dark ? 40 : 90 }} transition={morph} > <mask id={maskId}> <rect width="24" height="24" fill="white" /> <motion.circle r="6.5" fill="black" initial={false} animate={dark ? { cx: 16.5, cy: 7.5 } : { cx: 27, cy: -3 }} transition={morph} /> </mask> <motion.circle cx="12" cy="12" fill="currentColor" mask={`url(#${maskId})`} initial={false} animate={{ r: dark ? 8.5 : 5 }} transition={morph} /> <motion.g stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" initial={false} animate={dark ? { opacity: 0, scale: 0.5 } : { opacity: 1, scale: 1 }} transition={morph} > {rays.map(([x1, y1, x2, y2]) => ( <line key={`${x1}-${y1}`} x1={x1} y1={y1} x2={x2} y2={y2} /> ))} </motion.g> {/* Two stars twinkle in beside the moon. */} <motion.g fill="currentColor" initial={false} animate={dark ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }} transition={{ ...morph, delay: dark ? 0.15 : 0 }} > <path d="M19 2.6l.55 1.85L21.4 5l-1.85.55L19 7.4l-.55-1.85L16.6 5l1.85-.55z" /> <circle cx="21.2" cy="9.4" r="0.9" /> </motion.g> </motion.svg> ); } function resolveTarget(target: ThemeTarget | undefined): HTMLElement | null { if (typeof document === "undefined") return null; if (target === undefined) return document.documentElement; if (target === null) return null; if (typeof target === "function") return target(); if (target instanceof HTMLElement) return target; return target.current; } function applyTheme(el: HTMLElement | null, theme: Theme, darkClass: string) { if (!el) return; el.classList.toggle(darkClass, theme === "dark"); el.style.colorScheme = theme; } /** * A light/dark toggle whose icon morphs between a sun and a moon. The new * theme is revealed with a circle that grows out of the button, using the * View Transitions API; browsers without it (and reduced-motion users) get an * instant switch. * * It is not tied to a theme library: control it with `theme` / * `onThemeChange`, and it toggles a `dark` class on any target element * (the `<html>` element by default). Only the target is revealed, so the * effect can be scoped to a single panel. */ export function ThemeToggle({ theme: themeProp, defaultTheme = "dark", onThemeChange, target, applyClass = true, darkClass = "dark", transition = "circle", duration = 600, easing = "cubic-bezier(0.65, 0, 0.35, 1)", size = "default", variant = "outline", label = "Dark mode", className, ...props }: ThemeToggleProps) { const reduceMotion = useReducedMotion(); const buttonRef = React.useRef<HTMLButtonElement>(null); const busy = React.useRef(false); const [uncontrolled, setUncontrolled] = React.useState<Theme>(defaultTheme); const theme = themeProp ?? uncontrolled; const dark = theme === "dark"; // Latest values for the click handler, so the target can be a ref attached after mount. const latest = React.useRef({ target, applyClass, darkClass }); React.useLayoutEffect(() => { latest.current = { target, applyClass, darkClass }; }); // Keep the target in sync with the theme (mount and external changes). React.useEffect(() => { if (applyClass) applyTheme(resolveTarget(target), theme, darkClass); }, [theme, applyClass, darkClass, target]); const commit = (next: Theme) => { // flushSync renders the new theme before the browser takes the "after" snapshot. flushSync(() => { if (themeProp === undefined) setUncontrolled(next); onThemeChange?.(next); }); const { target: t, applyClass: apply, darkClass: cls } = latest.current; if (apply) applyTheme(resolveTarget(t), next, cls); }; const toggle = () => { if (busy.current) return; const next: Theme = dark ? "light" : "dark"; const el = resolveTarget(latest.current.target) ?? document.documentElement; const button = buttonRef.current; if ( transition === "none" || reduceMotion || typeof document.startViewTransition !== "function" || !button ) { commit(next); return; } // The root has a built-in name; any other target gets a temporary unique one. const isRoot = el === document.documentElement; const name = isRoot ? "root" : `theme-reveal-${Math.random().toString(36).slice(2, 9)}`; const style = document.createElement("style"); style.textContent = `::view-transition-old(${name}),::view-transition-new(${name}){animation:none;mix-blend-mode:normal}::view-transition-group(${name}){animation:none}`; document.head.appendChild(style); if (!isRoot) el.style.setProperty("view-transition-name", name); // Circle center in the target's coordinates; radius reaches its farthest corner. const b = button.getBoundingClientRect(); const t = isRoot ? { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight } : el.getBoundingClientRect(); const x = b.left + b.width / 2 - t.left; const y = b.top + b.height / 2 - t.top; const r = Math.hypot(Math.max(x, t.width - x), Math.max(y, t.height - y)); busy.current = true; const vt = document.startViewTransition(() => commit(next)); vt.ready .then(() => { document.documentElement.animate( { clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${r}px at ${x}px ${y}px)`] }, { duration, easing, pseudoElement: `::view-transition-new(${name})` } ); }) .catch(() => {}); const cleanup = () => { busy.current = false; style.remove(); if (!isRoot) el.style.removeProperty("view-transition-name"); }; vt.finished.then(cleanup, cleanup); }; return ( <button ref={buttonRef} type="button" aria-label={label} aria-pressed={dark} data-slot="theme-toggle" data-theme={theme} onClick={toggle} className={cn( "relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-full outline-none select-none", "transition-[background-color,transform,box-shadow] duration-150 active:scale-95 motion-reduce:active:scale-100", "focus-visible:ring-[3px] focus-visible:ring-ring/50", sizes[size], variants[variant], className )} {...props} > <SunMoonGlyph dark={dark} /> </button> ); }
On its own it toggles a dark class and color-scheme on <html>. Using next-themes? Pass its state in and set applyClass={false} so next-themes stays in charge of the class.
Usage
"use client"
import { useTheme } from "next-themes"
import { ThemeToggle } from "@/components/dusk/theme-toggle/theme-toggle"
export function SiteHeaderToggle() {
const { resolvedTheme, setTheme } = useTheme()
return (
<ThemeToggle
theme={resolvedTheme === "light" ? "light" : "dark"}
onThemeChange={setTheme}
applyClass={false}
/>
)
}Examples
Sizes, variants & speed
Three sizes, an outline or ghost look and a duration for the reveal. Each tile is its own target, so only that tile switches.
"use client";
import * as React from "react";
import { ThemeToggle, type ThemeToggleProps } from "@/components/dusk/theme-toggle/theme-toggle";
const palette =
"[--pv-bg:#fafafa] [--pv-fg:#18181b] [--pv-border:#e4e4e7] [&.dark]:[--pv-bg:#0b1411] [&.dark]:[--pv-fg:#f4f4f5] [&.dark]:[--pv-border:#1c2a25]";
const tiles: { label: string; props: Partial<ThemeToggleProps> }[] = [
{ label: "sm · ghost", props: { size: "sm", variant: "ghost" } },
{ label: "default", props: {} },
{ label: "lg · 1s reveal", props: { size: "lg", duration: 1000 } },
];
function Tile({ label, props }: (typeof tiles)[number]) {
const ref = React.useRef<HTMLDivElement>(null);
return (
<div
ref={ref}
className={`dark ${palette} flex w-36 flex-col items-center gap-3 rounded-xl border border-(--pv-border) bg-(--pv-bg) p-5 text-(--pv-fg)`}
>
<ThemeToggle target={ref} {...props} />
<span className="font-mono text-xs opacity-60">{label}</span>
</div>
);
}
export default function ThemeToggleSizesDemo() {
return (
<div className="flex flex-wrap justify-center gap-3">
{tiles.map((tile) => (
<Tile key={tile.label} {...tile} />
))}
</div>
);
}Controlled
Drive it with theme and onThemeChange. Clicks on the toggle get the circular reveal; changes made elsewhere apply instantly.
Reading mode
The toggle reveals the new theme from the button. Changing the theme from outside (the buttons below) updates the same state and switches instantly.
"use client";
import * as React from "react";
import { ThemeToggle, type Theme } from "@/components/dusk/theme-toggle/theme-toggle";
import { Button } from "@/components/ui/button";
const palette =
"[--pv-bg:#fffdf8] [--pv-fg:#1c1917] [--pv-muted:#78716c] [--pv-border:#e7e5e4] [&.dark]:[--pv-bg:#0c0f0e] [&.dark]:[--pv-fg:#e7e5e4] [&.dark]:[--pv-muted:#8a918e] [&.dark]:[--pv-border:#1f2624]";
export default function ThemeToggleControlledDemo() {
const article = React.useRef<HTMLElement>(null);
const [theme, setTheme] = React.useState<Theme>("dark");
return (
<div className="flex w-full max-w-md flex-col items-center gap-4">
<article
ref={article}
className={`dark ${palette} w-full rounded-xl border border-(--pv-border) bg-(--pv-bg) p-6 text-(--pv-fg)`}
>
<div className="mb-3 flex items-start justify-between gap-4">
<h3 className="font-serif text-xl font-semibold">Reading mode</h3>
<ThemeToggle theme={theme} onThemeChange={setTheme} target={article} size="sm" label="Dark reading mode" />
</div>
<p className="text-sm leading-relaxed text-(--pv-muted)">
The toggle reveals the new theme from the button. Changing the theme from outside (the
buttons below) updates the same state and switches instantly.
</p>
</article>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Button size="sm" aria-pressed={theme === "light"} variant={theme === "light" ? "default" : "outline"} onClick={() => setTheme("light")}>
Light
</Button>
<Button size="sm" aria-pressed={theme === "dark"} variant={theme === "dark" ? "default" : "outline"} onClick={() => setTheme("dark")}>
Dark
</Button>
<span className="ml-2 font-mono text-xs" aria-live="polite">
theme: {theme}
</span>
</div>
</div>
);
}API Reference
Also accepts any <button> attribute except onClick.
| Prop | Type | Default | Description |
|---|---|---|---|
| theme | "light" | "dark" | — | Current theme (controlled). |
| defaultTheme | "light" | "dark" | "dark" | Initial theme when uncontrolled. |
| onThemeChange | (theme) => void | — | Called with the next theme, inside the view transition so the new snapshot includes it. |
| target | RefObject<HTMLElement> | HTMLElement | () => HTMLElement | document.documentElement | Element that receives the dark class and is revealed. Pass a ref to scope the switch to one panel. |
| applyClass | boolean | true | Toggle darkClass and color-scheme on the target. Turn off when a theme library manages the class. |
| darkClass | string | "dark" | Class added to the target in dark mode. |
| transition | "circle" | "none" | "circle" | Circular reveal from the button, or an instant switch. |
| duration | number | 600 | Reveal duration in milliseconds. |
| easing | string | "cubic-bezier(0.65, 0, 0.35, 1)" | CSS easing for the reveal. |
| size | "sm" | "default" | "lg" | "default" | Button size. |
| variant | "outline" | "ghost" | "outline" | Button style. Colors follow currentColor, so they adapt to either theme. |
| label | string | "Dark mode" | Accessible name of the button. |
Accessibility
- It is a real
<button>witharia-pressed, so screen readers announce “Dark mode, toggle button, pressed” when dark mode is on. - Fully keyboard operable with Enter and Space, with a visible focus ring.
- With prefers-reduced-motion the theme switches instantly, with no circular reveal.
- Browsers without the View Transitions API get the same instant switch; nothing breaks.
- Setting
color-schemeon the target keeps native controls and scrollbars in the matching theme.