Switch
A toggle switch for binary on/off choices, with support for controlled, uncontrolled, and disabled states.
$npx shadcn add @patchui/switch
Controlled
Off
Default Checked
Starts on
Disabled
Disabled off
Disabled on
Usage
import { Switch } from "@patchui/react";
// Uncontrolled
<Switch defaultChecked />
// Controlled
const [checked, setChecked] = useState(false);
<Switch checked={checked} onCheckedChange={(c) => setChecked(c)} />
// Disabled
<Switch disabled />Props
| Prop | Type | Default | Description |
|---|---|---|---|
| checked | boolean | - | Whether the switch is currently active. Use for controlled switches. |
| defaultChecked | boolean | false | Whether the switch is initially active. Use for uncontrolled switches. |
| onCheckedChange | (checked: boolean, details) => void | - | Callback fired when the switch is toggled. |
| disabled | boolean | false | Disables the switch, preventing interaction. |
| readOnly | boolean | false | Prevents the user from toggling the switch. |
| required | boolean | false | Whether the switch must be active before submitting a form. |
| name | string | - | Identifies the field when a form is submitted. |
| className | string | - | Additional CSS classes applied to the switch root. |
Notes
- Switch vs Checkbox: Use a switch for settings that take effect immediately (e.g. "Enable notifications"). Use a checkbox for options that require a form submission.
- Accessibility: Renders a hidden
<input type="checkbox">for native form participation and assistive technology support. The switch has arole="switch"for screen readers. - Controlled vs uncontrolled: Use
checked+onCheckedChangefor controlled usage. UsedefaultCheckedfor uncontrolled.