Switch
An animated React toggle switch built on shadcn/ui and Radix: the drop-in Switch has a smoothly sliding thumb and three sizes — plus Motion blocks for a sun-to-moon theme toggle and an async switch that shows a spinner while saving and springs back if the request fails.
- Drop-in shadcn API
- Radix Switch
- CSS transitions
- Optimistic UI
- prefers-reduced-motion
"use client";
import * as React from "react";
import { Bell, BellOff } from "lucide-react";
import { IconSwitch } from "@/components/dusk/switch/icon-switch";
export default function IconSwitchDemo() {
const [dark, setDark] = React.useState(true);
return (
<div className="flex flex-wrap items-center justify-center gap-8">
<div className="flex items-center gap-3">
<IconSwitch checked={dark} onCheckedChange={setDark} aria-label="Dark mode" />
<span className="w-20 text-sm text-muted-foreground" aria-hidden>
{dark ? "Dark" : "Light"}
</span>
</div>
<IconSwitch
aria-label="Notifications"
defaultChecked
checkedIcon={<Bell />}
uncheckedIcon={<BellOff />}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/switch.json1. Install the dependencies.
npm install @radix-ui/react-switch class-variance-authority2. Copy the source into
components/ui/switch.tsx.switch.tsx "use client"; import * as React from "react"; import * as SwitchPrimitive from "@radix-ui/react-switch"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; /** * DuskUI Switch — a drop-in upgrade of the shadcn/ui Switch. * * Same API and data-slot attributes as shadcn plus: * - The thumb slides with a short ease-out (CSS only, no overshoot) and the * track turns mint when on. * - `size`: sm, default, lg. * - `thumbContent`: render an icon or spinner inside the thumb. * - `thumbClassName`: style the thumb without forking the component. * - RTL aware; under `prefers-reduced-motion` the thumb moves instantly. * Powered by Radix for keyboard support, form submission and aria. */ const switchVariants = cva( [ // border-2 + thumb = half the inner width, so the thumb travels exactly 100% of its size. "peer group/switch relative inline-flex shrink-0 items-center rounded-full border-2 border-transparent outline-none", "shadow-xs transition-[background-color,box-shadow] duration-150 ease-out motion-reduce:transition-none", "data-[state=unchecked]:bg-input data-[state=unchecked]:hover:bg-white/18", "data-[state=checked]:bg-primary", "focus-visible:ring-[3px] focus-visible:ring-ring/50", "aria-invalid:ring-[3px] aria-invalid:ring-destructive/40", "disabled:cursor-not-allowed disabled:opacity-50 aria-busy:cursor-wait", ], { variants: { size: { sm: "h-4 w-7", default: "h-5 w-9", lg: "h-6 w-11", }, }, defaultVariants: { size: "default", }, } ); const thumbSizes = { sm: "size-3", default: "size-4", lg: "size-5", } as const; export interface SwitchProps extends React.ComponentProps<typeof SwitchPrimitive.Root>, VariantProps<typeof switchVariants> { /** Content rendered inside the thumb, e.g. an icon or a spinner. */ thumbContent?: React.ReactNode; /** Classes for the thumb. */ thumbClassName?: string; } function Switch({ className, size, thumbContent, thumbClassName, ...props }: SwitchProps) { const resolved = size ?? "default"; return ( <SwitchPrimitive.Root data-slot="switch" data-size={resolved} className={cn(switchVariants({ size: resolved }), className)} {...props} > <SwitchPrimitive.Thumb data-slot="switch-thumb" className={cn( "pointer-events-none grid place-items-center overflow-hidden rounded-full ring-0", "shadow-sm", "data-[state=unchecked]:bg-foreground data-[state=checked]:bg-primary-foreground", "data-[state=checked]:translate-x-full rtl:data-[state=checked]:-translate-x-full", "[transition:translate_200ms_ease-out,background-color_150ms_ease-out]", "motion-reduce:[transition:background-color_150ms_ease-out]", "[&_svg]:pointer-events-none [&_svg]:shrink-0", thumbSizes[resolved], thumbClassName )} > {thumbContent} </SwitchPrimitive.Thumb> </SwitchPrimitive.Root> ); } export { Switch, switchVariants };
Replaces components/ui/switch.tsx with the same API. The thumb slides with a short CSS ease-out, so the base Switch runs no JavaScript per frame.
Usage
import { Switch } from "@/components/ui/switch"
export function AirplaneMode() {
return (
<div className="flex items-center gap-3">
<Switch id="airplane-mode" />
<label htmlFor="airplane-mode">Airplane mode</label>
</div>
)
}Examples
Default
Click or press Space: the thumb slides across and the track turns mint.
"use client";
import * as React from "react";
import { Switch } from "@/components/ui/switch";
export default function SwitchBasicDemo() {
const id = React.useId();
return (
<div className="flex items-center gap-3">
<Switch id={id} defaultChecked />
<label htmlFor={id} className="text-sm font-medium">
Airplane mode
</label>
</div>
);
}Sizes
size is sm, default or lg. Disabled switches dim and show a not-allowed cursor.
import { Switch } from "@/components/ui/switch";
export default function SwitchSizesDemo() {
return (
<>
<Switch size="sm" aria-label="Small switch" defaultChecked />
<Switch aria-label="Default switch" defaultChecked />
<Switch size="lg" aria-label="Large switch" defaultChecked />
<Switch aria-label="Disabled switch" disabled />
</>
);
}Settings list
Pair each switch with a <label> and link its hint with aria-describedby.
Email me when a production deploy finishes.
Notify me when someone @mentions me.
A Monday summary of activity.
"use client";
import * as React from "react";
import { Switch } from "@/components/ui/switch";
const settings = [
{ key: "deploys", title: "Deploy notifications", hint: "Email me when a production deploy finishes.", on: true },
{ key: "mentions", title: "Mentions", hint: "Notify me when someone @mentions me.", on: true },
{ key: "digest", title: "Weekly digest", hint: "A Monday summary of activity.", on: false },
];
export default function SwitchSettingsDemo() {
const id = React.useId();
return (
<div className="w-full max-w-md divide-y rounded-xl border bg-card">
{settings.map((s) => (
<div key={s.key} className="flex items-center justify-between gap-4 p-4">
<div className="grid gap-0.5">
<label htmlFor={`${id}-${s.key}`} className="text-sm font-medium">
{s.title}
</label>
<p id={`${id}-${s.key}-hint`} className="text-xs text-muted-foreground">
{s.hint}
</p>
</div>
<Switch id={`${id}-${s.key}`} aria-describedby={`${id}-${s.key}-hint`} defaultChecked={s.on} />
</div>
))}
</div>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Icon Switch
A theme toggle whose thumb morphs from a sun into a crescent moon: the rays spin and retract, the core swells and an SVG mask bites the crescent out. Pass checkedIcon and uncheckedIcon to spin between any two icons instead. The morph is also exported as SunMoonIcon.
"use client";
import * as React from "react";
import { Bell, BellOff } from "lucide-react";
import { IconSwitch } from "@/components/dusk/switch/icon-switch";
export default function IconSwitchDemo() {
const [dark, setDark] = React.useState(true);
return (
<div className="flex flex-wrap items-center justify-center gap-8">
<div className="flex items-center gap-3">
<IconSwitch checked={dark} onCheckedChange={setDark} aria-label="Dark mode" />
<span className="w-20 text-sm text-muted-foreground" aria-hidden>
{dark ? "Dark" : "Light"}
</span>
</div>
<IconSwitch
aria-label="Notifications"
defaultChecked
checkedIcon={<Bell />}
uncheckedIcon={<BellOff />}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/icon-switch.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/switch/icon-switch.tsx.icon-switch.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, type Transition } from "motion/react"; import { Switch, type SwitchProps } from "@/components/ui/switch"; import { cn } from "@/lib/utils"; export interface IconSwitchProps extends Omit<SwitchProps, "thumbContent" | "checked" | "defaultChecked"> { checked?: boolean; defaultChecked?: boolean; /** Icon shown in the thumb when on. Omit both icons for the built-in sun → moon morph. */ checkedIcon?: React.ReactNode; /** Icon shown in the thumb when off. */ uncheckedIcon?: React.ReactNode; } const morph: Transition = { type: "spring", bounce: 0.1, duration: 0.4 }; // Precomputed so server and client render identical markup. const rays = [ [20, 12, 22.5, 12], [17.66, 17.66, 19.42, 19.42], [12, 20, 12, 22.5], [6.34, 17.66, 4.58, 19.42], [4, 12, 1.5, 12], [6.34, 6.34, 4.58, 4.58], [12, 4, 12, 1.5], [17.66, 6.34, 19.42, 4.58], ] as const; /** * A single SVG that morphs between a sun and a crescent moon: the rays spin * and retract, the core swells and a mask "bites" the crescent out of it. */ export function SunMoonIcon({ moon, className }: { moon: boolean; className?: string }) { const maskId = `sun-moon-${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; return ( <motion.svg viewBox="0 0 24 24" aria-hidden className={className} initial={false} animate={{ rotate: moon ? -30 : 0 }} transition={morph} > <mask id={maskId}> <rect width="24" height="24" fill="white" /> <motion.circle r="7" fill="black" initial={false} animate={moon ? { cx: 18, cy: 6 } : { cx: 30, cy: -6 }} transition={morph} /> </mask> <motion.circle cx="12" cy="12" fill="currentColor" mask={`url(#${maskId})`} initial={false} animate={{ r: moon ? 9 : 4.5 }} transition={morph} /> <motion.g stroke="currentColor" strokeWidth={2} strokeLinecap="round" initial={false} animate={moon ? { opacity: 0, scale: 0.4, rotate: -90 } : { opacity: 1, scale: 1, rotate: 0 }} transition={morph} > {rays.map(([x1, y1, x2, y2]) => ( <line key={`${x1}-${y1}`} x1={x1} y1={y1} x2={x2} y2={y2} /> ))} </motion.g> </motion.svg> ); } const swap = { initial: { opacity: 0, scale: 0.6, rotate: -45 }, animate: { opacity: 1, scale: 1, rotate: 0 }, exit: { opacity: 0, scale: 0.6, rotate: 45 }, transition: { type: "spring", bounce: 0.1, duration: 0.3 }, } as const; /** * A switch with an icon inside the thumb. By default it is a theme toggle * whose thumb morphs from a sun into a moon; pass `checkedIcon` / * `uncheckedIcon` to spin between any two icons instead. * Built on the DuskUI Switch (Radix), so it submits with forms and is keyboard accessible. */ export function IconSwitch({ checked: checkedProp, defaultChecked = false, onCheckedChange, checkedIcon, uncheckedIcon, size = "lg", thumbClassName, ...props }: IconSwitchProps) { const [uncontrolled, setUncontrolled] = React.useState(defaultChecked); const checked = checkedProp ?? uncontrolled; const custom = checkedIcon !== undefined || uncheckedIcon !== undefined; return ( <Switch size={size} checked={checked} onCheckedChange={(next) => { if (checkedProp === undefined) setUncontrolled(next); onCheckedChange?.(next); }} thumbClassName={cn( "data-[state=unchecked]:text-background data-[state=checked]:text-foreground [&_svg]:size-[70%]", thumbClassName )} thumbContent={ custom ? ( <AnimatePresence initial={false} mode="popLayout"> <motion.span key={checked ? "on" : "off"} className="grid size-full place-items-center" {...swap}> {checked ? checkedIcon : uncheckedIcon} </motion.span> </AnimatePresence> ) : ( <SunMoonIcon moon={checked} /> ) } {...props} /> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| checked / onCheckedChange | boolean / (checked: boolean) => void | — | Controlled state. |
| defaultChecked | boolean | false | Uncontrolled initial state. |
| checkedIcon / uncheckedIcon | ReactNode | — | Custom icons. Omit both for the sun / moon morph. |
| size | "sm" | "default" | "lg" | "lg" | Switch size; lg leaves room for the icon. |
| thumbClassName | string | — | Classes for the thumb, e.g. icon colors. |
Loading Switch
For settings that save to a server. Return a promise from onCheckedChange: the switch moves optimistically, shows a spinner inside the thumb and ignores clicks until it settles. If the promise rejects it springs back with a short shake and a red ring. The second row always fails.
"use client";
import * as React from "react";
import { LoadingSwitch } from "@/components/dusk/switch/loading-switch";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default function LoadingSwitchDemo() {
const id = React.useId();
return (
<div className="grid w-full max-w-sm gap-4">
<div className="flex items-center justify-between gap-4 rounded-xl border bg-card p-4">
<label htmlFor={`${id}-ok`} className="text-sm font-medium">
Public profile
</label>
<LoadingSwitch id={`${id}-ok`} defaultChecked onCheckedChange={() => wait(1200)} />
</div>
<div className="flex items-center justify-between gap-4 rounded-xl border bg-card p-4">
<label htmlFor={`${id}-fail`} className="grid gap-0.5 text-sm font-medium">
Beta features
<span className="text-xs font-normal text-muted-foreground">Always fails, to show the revert.</span>
</label>
<LoadingSwitch
id={`${id}-fail`}
onCheckedChange={async () => {
await wait(1000);
throw new Error("Network error");
}}
/>
</div>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/loading-switch.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/switch/loading-switch.tsx.loading-switch.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useAnimate, useReducedMotion } from "motion/react"; import { Switch, type SwitchProps } from "@/components/ui/switch"; import { cn } from "@/lib/utils"; export interface LoadingSwitchProps extends Omit<SwitchProps, "thumbContent" | "checked" | "defaultChecked" | "onCheckedChange"> { checked?: boolean; defaultChecked?: boolean; /** * Called with the requested state. Return a promise to show a spinner in the * thumb until it settles; if it rejects, the switch springs back and shakes. * When controlled, update `checked` inside the handler once the save succeeds. */ onCheckedChange?: (checked: boolean) => void | Promise<unknown>; /** Called with the rejection reason when the promise fails. */ onError?: (error: unknown) => void; /** Force the busy state from outside (e.g. while initial data loads). */ loading?: boolean; /** Announced to screen readers while saving. */ loadingLabel?: string; /** Announced to screen readers when the change is reverted. */ errorLabel?: string; } function isPromise(value: unknown): value is Promise<unknown> { return !!value && typeof (value as Promise<unknown>).then === "function"; } /** * A switch for settings that save to a server. It moves optimistically, shows * a spinner inside the thumb while `onCheckedChange` resolves, ignores extra * clicks while busy, and on failure springs back with a short shake and a red * ring. Progress and errors are announced politely to screen readers. */ export function LoadingSwitch({ checked: checkedProp, defaultChecked = false, onCheckedChange, onError, loading = false, loadingLabel = "Saving", errorLabel = "Couldn't save. Change reverted.", className, thumbClassName, ...props }: LoadingSwitchProps) { const reduceMotion = useReducedMotion(); const [scope, animate] = useAnimate<HTMLSpanElement>(); const [uncontrolled, setUncontrolled] = React.useState(defaultChecked); // The value we're saving, shown optimistically until the promise settles. const [pending, setPending] = React.useState<boolean | null>(null); const [failed, setFailed] = React.useState(false); const mounted = React.useRef(true); const errorTimer = React.useRef<ReturnType<typeof setTimeout>>(undefined); React.useEffect(() => { mounted.current = true; return () => { mounted.current = false; clearTimeout(errorTimer.current); }; }, []); const committed = checkedProp ?? uncontrolled; const shown = pending ?? committed; const busy = pending !== null || loading; const handleChange = async (next: boolean) => { if (busy) return; clearTimeout(errorTimer.current); setFailed(false); let result: void | Promise<unknown>; try { result = onCheckedChange?.(next); } catch (error) { onError?.(error); return; } if (!isPromise(result)) { if (checkedProp === undefined) setUncontrolled(next); return; } setPending(next); try { await result; if (mounted.current && checkedProp === undefined) setUncontrolled(next); } catch (error) { onError?.(error); if (!mounted.current) return; setFailed(true); errorTimer.current = setTimeout(() => setFailed(false), 2400); if (!reduceMotion && scope.current) { animate(scope.current, { x: [0, -3, 3, -2, 0] }, { duration: 0.3, delay: 0.15 }); } } finally { if (mounted.current) setPending(null); } }; return ( <span ref={scope} data-slot="loading-switch" className="relative inline-flex"> <Switch checked={shown} onCheckedChange={handleChange} aria-busy={busy || undefined} data-error={failed || undefined} className={cn("data-error:ring-[3px] data-error:ring-destructive/50", className)} thumbClassName={cn("text-background data-[state=checked]:text-foreground", thumbClassName)} thumbContent={ <AnimatePresence initial={false}> {busy && ( <motion.svg key="spinner" viewBox="0 0 24 24" fill="none" aria-hidden className="size-[70%]" initial={{ opacity: 0, scale: 0.4 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.4 }} transition={{ type: "spring", bounce: 0, duration: 0.25 }} > <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity={0.25} strokeWidth={3} /> <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth={3} strokeLinecap="round" className="origin-center animate-spin [animation-duration:0.7s] motion-reduce:[animation-duration:1.6s]" /> </motion.svg> )} </AnimatePresence> } {...props} /> <span role="status" className="sr-only"> {pending !== null ? loadingLabel : failed ? errorLabel : ""} </span> </span> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| onCheckedChange | (checked: boolean) => void | Promise<unknown> | — | Return a promise to show the spinner; reject to revert. |
| checked / defaultChecked | boolean | — | Controlled or initial state. When controlled, update checked inside the handler. |
| onError | (error: unknown) => void | — | Called with the rejection reason. |
| loading | boolean | false | Force the busy state, e.g. while initial data loads. |
| loadingLabel / errorLabel | string | "Saving" / "Couldn't save…" | Announced to screen readers. |
API Reference
Switch forwards every Radix Switch prop (checked, defaultChecked, onCheckedChange, disabled, required, name, value) plus the additions below.
| Prop | Type | Default | Description |
|---|---|---|---|
| size | "sm" | "default" | "lg" | "default" | Track and thumb size. |
| thumbContent | ReactNode | — | Rendered inside the thumb (an icon or spinner). |
| thumbClassName | string | — | Classes for the thumb. |
| className | string | — | Classes for the track. Keep width = 2 × thumb + 4px so the thumb travels exactly. |
Accessibility
- Built on Radix Switch: a button with role="switch" and aria-checked, toggled with Space or Enter, and submitted with forms through a hidden input.
- Give every switch a visible
<label htmlFor>or anaria-label. - Loading Switch sets
aria-busy, stays focusable while saving and announces progress and failures in a polite live region. - Under prefers-reduced-motion the thumb moves instantly, the error shake is skipped and the spinner slows down.