Components
Switch
A toggle switch component for boolean inputs
Switch
The Switch component is a toggle switch for boolean inputs. Built on Radix UI primitives for full accessibility and smooth animations.
Installation
npm install @nqlib/nquiImport
import { Switch } from '@nqlib/nqui';Basic Usage
import { Switch, Label } from '@nqlib/nqui';
export default function Example() {
return (
<div className="flex items-center gap-2">
<Switch id="notifications" />
<Label htmlFor="notifications">Enable notifications</Label>
</div>
);
}Examples
Basic Switch
Controlled Switch
Default Checked
Disabled States
Switch Group
With Label
Always pair switches with labels for accessibility:
import { Switch, Label } from '@nqlib/nqui';
<div className="flex items-center gap-2">
<Switch id="notifications" />
<Label htmlFor="notifications">Enable notifications</Label>
</div>Controlled Switch
Use controlled state for programmatic control:
const [enabled, setEnabled] = useState(false);
<Switch checked={enabled} onCheckedChange={setEnabled} />Uncontrolled Switch
Use defaultChecked for uncontrolled state:
<Switch defaultChecked />Disabled State
<Switch disabled />
<Switch disabled defaultChecked />Props
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | - | Controlled checked state |
defaultChecked | boolean | false | Uncontrolled default checked state |
onCheckedChange | (checked: boolean) => void | - | Callback when checked state changes |
disabled | boolean | false | Whether the switch is disabled |
required | boolean | false | Whether the switch is required |
name | string | - | Form field name |
value | string | - | Form field value |
className | string | - | Additional CSS classes |
Styling
Switches use the following design tokens:
- Track (unchecked):
bg-input - Track (checked):
bg-primary - Thumb:
bg-backgroundwith shadow - Border:
border-transparent - Focus ring:
ring-ringwithring-offset-background - Disabled:
opacity-50withcursor-not-allowed
Accessibility
- Full keyboard navigation support
- ARIA attributes for screen readers
- Focus management with visible focus rings
- Proper label association
- Disabled state handling
- Toggle semantics
Best Practices
- Always use labels: Pair every switch with a label for accessibility
- Use for boolean toggles: Switches are ideal for on/off settings
- Provide clear labels: Use descriptive labels that indicate what the switch controls
- Handle disabled states: Clearly indicate when switches are disabled
- Consider grouping: Group related switches together
Next Steps
- Learn about Checkbox for multiple selections
- Explore RadioGroup for single selection
- Check out Field component for form field wrapper
- See Form Components for other form elements