Switches the next-themes theme inside a View Transition. Four variants are built in: fade, scale, slide, and circle, where the new theme grows out of the click point. The transition styles are injected only for the duration of the animation and removed afterwards. Where the API is missing or reduced motion is on, the theme changes instantly.
Browser Support
Animates the theme change.
Preview
The buttons switch the real site theme. Each one uses its own variant.
Installation
Usage
import { ThemeTransitionToggle } from "@/components/ui/theme-transition"
// Inside a next-themes <ThemeProvider attribute="class">
export function Header() {
return (
<header className="flex justify-end p-4">
<ThemeTransitionToggle />
</header>
)
}Examples
Hook with your own button
useThemeTransition returns everything useTheme does, plus setTheme with an origin point and toggleTheme.
import { Button } from "@/components/ui/button"
"use client"
import {
getTransitionOrigin,
useThemeTransition,
} from "@/components/ui/theme-transition"
export function ThemeSwitch() {
const { resolvedTheme, toggleTheme } = useThemeTransition()
return (
<Button onClick={(event) => toggleTheme(getTransitionOrigin(event))}>
{resolvedTheme === "dark" ? "Light mode" : "Dark mode"}
</Button>
)
}Choosing a variant
Pass variant, duration and easing to the hook or the toggle. Without an origin the circle grows from the viewport center.
<ThemeTransitionToggle variant="slide" duration={700} easing="cubic-bezier(.7,0,.3,1)" />
const { toggleTheme } = useThemeTransition({ variant: "fade", duration: 300 })Theme menu
setTheme accepts any theme name, including system. getTransitionOrigin turns a click into a point and uses the element center for keyboard presses.
import { Button } from "@/components/ui/button"
const { setTheme } = useThemeTransition({ variant: "circle" })
{["light", "dark", "system"].map((name) => (
<Button key={name} onClick={(event) => setTheme(name, getTransitionOrigin(event))}>
{name}
</Button>
))}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| variant | "fade" | "scale" | "slide" | "circle" | "circle" | Transition style |
| duration | number | 500 | Duration, in ms |
| easing | string | "ease-in-out" | CSS easing function |
| labels | { toLight?: string; toDark?: string } | - | Accessible labels of the toggle |
| className | string | - | Additional CSS classes of the toggle |
useThemeTransition Accepts { variant, duration, easing } and returns the useTheme result with setTheme(theme, origin?) and toggleTheme(origin?).