Switch
A switch for a binary setting.
Overview
Switch renders a native button with role="switch". Click, Space, and Enter toggle it. That is the button's own keyboard behavior.
It does not participate in native form submission. name and value are present on the button, and a type="button" is not a successful form control. Use Checkbox when the choice should be submitted.
Preview
Customize
Installation
Add the component with the CLI. It copies the files in and installs anything they depend on.
npx vinyaas add switchUsage
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export function Alerts() {
return (
<div className="flex items-center gap-3">
<Switch id="alerts" />
<Label htmlFor="alerts">Alerts</Label>
</div>
);
}Examples
Basic
An uncontrolled switch starts off.
Controlled
checked and onCheckedChange keep the state in the parent.
Disabled
A disabled switch keeps its current state and ignores clicks.
Label
htmlFor matches the switch id. Clicking the label toggles it.
Form
The switch is a button, so name and value are not included in the submitted form data. Use Checkbox when the value must be submitted.
In practice
Notification channels use labelled switches. Save settings is the form action; the switches themselves are not submitted.
API
Other attributes for the underlying element are passed through.
| Name | Type | Default | Description |
|---|---|---|---|
checked | boolean | — | Controlled on state. Omit it for an uncontrolled switch. |
defaultChecked | boolean | false | Initial on state for an uncontrolled switch. |
onCheckedChange | (checked: boolean) => void | — | Called with the next state after a click. |
disabled | boolean | — | Native disabled button. It cannot be toggled. |
name | string | — | Set on the button. A switch is not submitted with the form. |
value | string | — | Set on the button. It is not included in form data. |
required | boolean | — | Passed through to the button. It does not constrain the form. |
className | string | — | Merged onto the button with cn. |
Accessibility
The control is a button with role="switch" and aria-checked. It does not add aria-disabled.
- Name it with a label and matching id, or with aria-label.
- Space and Enter toggle it when it has focus.
- disabled blocks activation. The control stays in the tree.
- Focus uses a visible focus-visible ring.