Switch
Toggles a setting or preference between on and off states. Ideal for binary options in forms or settings.
Code
Installation
npx shadcn@latest add switchBasic Example
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
const [checked, setChecked] = useState(false)
<div className="flex items-center space-x-2">
<Switch
id="notifications"
checked={checked}
onCheckedChange={setChecked}
/>
<Label htmlFor="notifications" className="cursor-pointer">
Enable notifications
</Label>
</div>Reference
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| checked | boolean | — | Controlled checked state |
| defaultChecked | boolean | false | Default checked state (uncontrolled) |
| variant | string | "primary" | Visual variant. Options: primary, neutral, success |
| onCheckedChange | function | — | Callback when checked state changes |
| disabled | boolean | false | Disable the switch |
Variants
States
Usage Guidelines
When to Use
Use switches for toggling settings, preferences, and binary options that have immediate effect. They work well for enabling/disabling features, changing modes, and controlling application behavior.
Switches are ideal when the change takes effect immediately without requiring additional confirmation. For actions that need confirmation, consider using checkboxes with a save button instead.
Best Practices
- Always provide clear labels for switches
- Use neutral variant for subtle settings
- Use success variant for positive actions
- Group related switches together
- Provide context with helper text when needed
Accessibility
Switches are fully keyboard accessible. Users can toggle with Space and navigate with Tab. Always associate labels with switches using htmlFor and id attributes for proper screen reader support.
Use the Label component with cursor-pointer class to make the entire label area clickable. Ensure switch labels clearly describe what will happen when toggled.