Switch
A simple switch component on top of the native checkbox.
import { Switch } from "@/components/switch";
export default function SwitchPreview() {
return <Switch />;
}Source Code
import { cn } from "@/lib/utils/classnames";
const Switch = ({ className, ...props }: Omit<React.ComponentPropsWithRef<"input">, "type">) => {
return (
<input
type="checkbox"
// biome-ignore lint/a11y/useAriaPropsForRole: native checkbox supplies the implicit aria-checked state
role="switch"
className={cn(
"appearance-none",
"relative h-6 w-11 cursor-pointer rounded-full bg-foreground/20 transition",
// circle
"before:absolute before:top-0.5 before:left-0.5 before:size-5 before:rounded-full before:bg-background before:transition-transform before:duration-200 before:ease-emphasized-decelerate",
// disabled
"disabled:before:opacity-30",
// checked
"checked:bg-foreground checked:before:translate-x-full",
// focus
"focus-visible:ring-(length:--ring-width) focus-visible:outline-none focus-visible:ring-ring",
// stretch animation
"before:origin-left active:before:scale-x-110 active:checked:before:origin-right",
className,
)}
{...props}
/>
);
};
export { Switch };API Reference
Extends the native input element with type="checkbox".
Examples
Simple
Basic usage of the switch component.
import { Switch } from "@/components/switch";
export default function SwitchPreview() {
return <Switch />;
}Disabled
Example of a disabled switch.
import { Switch } from "@/components/switch";
export default function SwitchDisabled() {
return <Switch disabled />;
}Disabled Checked
Example of a disabled switch in the checked state.
import { Switch } from "@/components/switch";
export default function SwitchDisabledChecked() {
return <Switch disabled checked />;
}Custom style
Example showing custom styling options.
import { Switch } from "@/components/switch";
export default function SwitchCustomStyle() {
return <Switch className="bg-blue-400/20 checked:bg-blue-500" />;
}Best Practices
-
Usage:
- Use for immediate actions
- Provide clear labels
- Consider state persistence
-
Accessibility:
- Use clear state indicators
Previous
Spinner
Next
Table