Switch Component
The Switch component provides a toggle switch for boolean inputs. It's perfect for settings, preferences, and on/off states.
Basic Usage
import { Switch } from 'nebula-ui';
import { useState } from 'react';
export default function Example() {
const [enabled, setEnabled] = useState(false);
return (
<Switch
checked={enabled}
onCheckedChange={setEnabled}
label="Enable notifications"
/>
);
}With Label
Add a label to describe what the switch controls:
<Switch
checked={darkMode}
onCheckedChange={setDarkMode}
label="Dark mode"
/>Controlled Component
Use controlled state for the switch:
const [enabled, setEnabled] = useState(false);
<Switch
checked={enabled}
onCheckedChange={setEnabled}
label="Enable feature"
/>Uncontrolled Component
You can also use it without a label:
<Switch
checked={isEnabled}
onCheckedChange={(checked) => console.log(checked)}
/>Disabled State
Disable the switch to prevent interactions:
<Switch
checked={false}
disabled
label="Disabled switch"
/>
<Switch
checked={true}
disabled
label="Disabled checked"
/>Full Width
Make the switch span the full width:
<Switch
checked={enabled}
onCheckedChange={setEnabled}
label="Full width switch"
fullWidth
/>Props
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | false | Whether the switch is checked |
onCheckedChange | (checked: boolean) => void | - | Callback when switch state changes |
disabled | boolean | false | Disable the switch |
label | string | - | Label text |
fullWidth | boolean | false | Makes switch full width |
Accessibility
The Switch component is fully accessible:
- Keyboard navigation support (Space/Enter to toggle)
- Proper ARIA attributes (
role="switch",aria-checked) - Screen reader support
- Focus management
Examples
Settings Panel
<div className="space-y-4">
<Switch
checked={notifications}
onCheckedChange={setNotifications}
label="Email notifications"
/>
<Switch
checked={darkMode}
onCheckedChange={setDarkMode}
label="Dark mode"
/>
<Switch
checked={autoSave}
onCheckedChange={setAutoSave}
label="Auto-save"
/>
</div>Feature Toggle
<Switch
checked={featureEnabled}
onCheckedChange={(checked) => {
setFeatureEnabled(checked);
// Additional logic here
}}
label="Enable new feature"
/>Best Practices
- Always provide a label to describe what the switch controls
- Use for boolean settings - switches are ideal for on/off states
- Provide immediate feedback - changes should take effect immediately
- Group related switches together in a settings panel
- Use disabled state when the switch cannot be changed
Was this page helpful?
Let us know if this documentation helped you.