Switch
A toggle switch for boolean settings with default and compact size variants.
Installation
$
Usage
import { Switch } from "@/components/ui/switch"Examples
Default
Small
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| size | "sm" | "default" | "default" | Track size. default is 20×32px; sm is a compact 16×24px. |
| checked | boolean | - | Controlled on/off state. Pair with onCheckedChange. |
| defaultChecked | boolean | false | Initial state when uncontrolled. |
| onCheckedChange | (checked: boolean) => void | - | Called with the new state whenever the switch is toggled. |
| disabled | boolean | false | Prevents interaction and dims the control. |
| name | string | - | Name submitted with the owning form's data. |
| value | string | "on" | Value submitted with the form when the switch is on. |
"use client"
import * as React from "react"
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "@/registry/lib/utils"
function Switch({
className,
size = "default",
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
size?: "sm" | "default"
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer group/switch relative inline-flex shrink-0 items-center rounded-full shadow-xs outline-none transition-[color,background-color,transform] duration-150 motion-reduce:transition-none data-[unchecked]:bg-neutral-300 dark:data-[unchecked]:bg-neutral-700 data-[checked]:bg-accent focus-visible:ring-ring-focus focus-visible:ring-[3px] active:scale-[0.98] data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[size=default]:h-5 data-[size=default]:w-8 data-[size=sm]:h-4 data-[size=sm]:w-6 pointer-coarse:before:absolute pointer-coarse:before:-inset-x-2 pointer-coarse:before:-inset-y-3 pointer-coarse:before:content-['']",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-neutral-50 shadow-sm pointer-events-none block rounded-full ring-0 transition-transform duration-150 motion-reduce:transition-none group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[checked]:translate-x-[calc(100%-2px)] data-[unchecked]:translate-x-0.5"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }