Switch
FreeA glass switch for a setting that takes effect at once: the capsule knob springs across, turns into a clear lens while held, and puts itself back if the save fails.
npx shadcn@latest add https://pixilui.com/r/switch.jsonPreview
The knob springs across and clears into a lens while held.
Save
import { useState } from "react";
import { SwitchRow } from "@/components/pixilui/switch";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
save: ["instant", "fails"],
} as const;
const settings = [
{ id: "alerts", label: "Approval alerts", note: "Tell me when a run is waiting on me", on: true },
{ id: "summary", label: "Weekly usage summary", note: "Every Monday at 9:00 am", on: false },
{ id: "retry", label: "Retry failed runs", note: "Up to 2 times, then it waits for you", on: true },
{ id: "share", label: "Share runs with the workspace", note: "Your admin turned this off", on: false, disabled: true },
];
/** A notifications card; "fails" makes every save reject after 700ms so the switch puts itself back. */
export default function SwitchDemo({ save = "instant" }: KnobValues<typeof knobs>) {
return (
<div className="w-full max-w-md rounded-panel bg-surface px-5 py-3 elevation-raised">
{settings.map((s) => (
<Setting key={`${s.id}-${save}`} {...s} fails={save === "fails"} />
))}
</div>
);
}
function Setting({ label, note, on, disabled, fails }: { id: string; label: string; note: string; on: boolean; disabled?: boolean; fails: boolean }) {
const [checked, setChecked] = useState(on);
return (
<SwitchRow
label={label}
description={note}
disabled={disabled}
checked={checked}
onCheckedChange={(next) => {
if (!fails) return setChecked(next);
return new Promise<void>((_, reject) => setTimeout(() => reject(new Error("Not saved")), 700));
}}
/>
);
}When to use
Use it when
- A setting that applies the moment it flips: alerts, retries, sharing.
- A settings list, label and second line on the left, the switch on the right (SwitchRow).
Use something else when
- A choice saved later with a form's submit: use Checkbox.
- One choice among several: use Radio group or a segmented control.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/switch.jsonAdds switch.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
components/pixilui/switch.tsx
"use client";
/*
The switch, locked 27 Nov 2026 with the toggles (design/explorations/components/locked/toggles). Its
look and motion are foundation.css section 8 (.pixilui-switch); this file writes the locked markup and
plays the locked behavior (toggles.js):
Track a 44 x 20 pale glass track; on, the candy glass cross-fades in (200ms) with its edge and glow.
Knob a 24 x 16 glass capsule that crosses with a small overshoot (300ms); while pressed it widens
4px toward where it will go and turns into a clear lens.
Hover an off switch shows a 22% wash of the color.
Pending onCheckedChange may return a promise: the switch shows the new state at once, is aria-busy
until it settles, and goes back if it rejects. No spinner: the lock rejected it.
Reduced instant.
*/
import { forwardRef, useId, useState, type ComponentPropsWithoutRef, type MouseEvent, type ReactNode } from "react";
import { cn } from "./lib/utils";
export type SwitchProps = Omit<ComponentPropsWithoutRef<"button">, "onChange" | "value" | "defaultValue" | "children" | "role"> & {
/** Controlled: on or off. */
checked?: boolean;
/** Uncontrolled: the state on the first render. */
defaultChecked?: boolean;
/**
* Runs with the new state on a click, Space or Enter. Return a promise to save first: the switch shows the
* new state, is aria-busy until it settles, and goes back if it rejects.
*/
onCheckedChange?: (checked: boolean) => void | Promise<void>;
/** A form field name: a hidden input carries value while the switch is on. */
name?: string;
/** The value sent with the form while on. */
value?: string;
};
/** A setting that takes effect at once: a glass track whose capsule knob springs across. Give it an aria-label, or put it in a SwitchRow. */
export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(function Switch(
{ checked, defaultChecked = false, onCheckedChange, name, value = "on", disabled, onClick, className, ...props },
ref,
) {
const [own, setOwn] = useState(defaultChecked);
const [pending, setPending] = useState<boolean | null>(null);
const shown = pending ?? checked ?? own;
const flip = async (event: MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented || disabled || pending !== null) return;
const next = !shown;
if (checked === undefined) setOwn(next);
const result = onCheckedChange?.(next);
if (!result || typeof (result as Promise<void>).then !== "function") return;
setPending(next);
try {
await result;
} catch {
if (checked === undefined) setOwn(!next);
} finally {
setPending(null);
}
};
return (
<>
<button
ref={ref}
type="button"
role="switch"
aria-checked={shown ? "true" : "false"}
aria-busy={pending !== null || undefined}
disabled={disabled}
className={cn("pixilui-switch focus-visible:focus-ring", className)}
onClick={flip}
{...props}
>
<span className="pixilui-switch-knob" aria-hidden="true" />
</button>
{name && shown && <input type="hidden" name={name} value={value} />}
</>
);
});
export type SwitchRowProps = SwitchProps & {
/** The row's label: names the switch, and a click on it reaches the switch. */
label: ReactNode;
/** A second line under the label. */
description?: ReactNode;
/** Sets the second line in the warning color, for a setting with a cost. */
risk?: boolean;
/** Class for the row (className goes to the switch). */
rowClassName?: string;
};
/** A setting row: the label and its second line on the left, the switch on the right; the whole row clicks. */
export const SwitchRow = forwardRef<HTMLButtonElement, SwitchRowProps>(function SwitchRow(
{ label, description, risk, rowClassName, "aria-label": ariaLabel, ...props },
ref,
) {
const id = useId();
return (
<label className={cn("pixilui-toggle-row font-body", rowClassName)} data-align="end">
<span className="pixilui-toggle-row-text">
<b>{label}</b>
{description && (
<small id={`${id}-d`} data-tone={risk ? "risk" : undefined}>
{description}
</small>
)}
</span>
<Switch ref={ref} aria-label={ariaLabel ?? (typeof label === "string" ? label : undefined)} aria-describedby={description ? `${id}-d` : undefined} {...props} />
</label>
);
});
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { Switch } from "@/components/pixilui/switch";
<Switch onCheckedChange={onCheckedChange}>Save changes</Switch>44 by 20 at every width; a row's words wrap and the switch stays at the end.
API reference
PropTypeDefault
namestring–A form field name: a hidden input carries value while the switch is on.defaultCheckedbooleanfalseUncontrolled: the state on the first render.checkedboolean–Controlled: on or off.onCheckedChange(checked: boolean) => void | Promise<void>–Runs with the new state on a click, Space or Enter. Return a promise to save first: the switch shows the new state, is aria-busy until it settles, and goes back if it rejects.valuestring"on"The value sent with the form while on.Also takes every native <button> attribute except onChange, value, defaultValue, role, and a ref.
Keyboard
TabMoves to each switch in turn.
Space EnterFlips the focused switch.
Accessibility
- A button with role="switch" and aria-checked.
- In a SwitchRow the label names it and the second line describes it (aria-describedby); alone, give it an aria-label.
- The row is a label, so a click on the words flips it once.
- While a returned promise is pending the switch is aria-busy and keeps its focus.
Motion
- The knob crosses in 300ms with a small overshoot; the candy glass cross-fades in over 200ms with its edge and glow.
- Held, the knob widens 4px toward where it will go and turns into a clear lens in 150ms.
- Hover on an off switch shows a 22% wash of the color.
- Reduced motion: instant.