Switch
The Switch component provides a toggle switch alternative to checkboxes with support for labels, different sizes, and form integration. It's designed for binary choices where the user can toggle between enabled and disabled states.
Examples
Basic Usage
<Switch label="Enable notifications" />With Initial Value
<Switch
label="Dark mode"
checked={true}
/>Different Sizes
<Switch
label="Small"
size="sm"
/>
<Switch
label="Medium (default)"
size="md"
/>
<Switch
label="Large"
size="lg"
/>Disabled State
<Switch
label="Disabled (off)"
disabled={true}
/>
<Switch
label="Disabled (on)"
checked={true}
disabled={true}
/>Required Field
<Switch
label="I agree to the terms"
required={true}
/>Without Label
Airplane mode
<div class="flex items-center gap-2">
<span>Airplane mode</span>
<Switch ariaLabel="Toggle airplane mode" />
</div>Props
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | false | Whether the switch is checked |
label | string | Required | Label text for the switch |
name | string | Required | Name attribute for the input |
disabled | boolean | false | Whether the switch is disabled |
required | boolean | false | Whether the switch is required |
size | 'sm' | 'md' | 'lg' | 'md' | Size of the switch |
ariaLabel | string | Required | ARIA label for accessibility (used when no visible label is provided) |
id | string | auto-generated | HTML id for accessibility |
class | string | '' | Additional CSS classes |
Events
| Event | Detail Type | Description |
|---|---|---|
onchange | { checked: boolean } | Fired when the switch state changes |
Accessibility
The Switch component follows accessibility best practices:
- Uses a native
<input type="checkbox">for best compatibility - Proper focus states with visible indicators
- Labels are properly associated with inputs
- ARIA labels for switches without visible labels
- Proper disabled states with visual indicators
- High color contrast between track and thumb
- Smooth transitions for state changes
Keyboard Interaction
Tab- Move focus to the switchSpace- Toggle the switch state