Switch
A toggle switch component for binary on/off states with smooth animations
Installation
Terminal
Import
Component.tsx
Basic
The `Switch` component is a toggle control for binary states like on/off or enabled/disabled.
It is a controlled component that requires a `value` prop and an `onChange` prop.
Features:
- Multiple visual variants (default, accent, outline)
- Two sizes (small, medium)
- Support for disabled and focused states
- Two label approaches: simple string children or explicit `<Switch.Label>` for complex content
- Full keyboard and screen reader accessibility
Usage Guidelines:
- Use for immediate toggle actions (unlike checkboxes in forms)
- Provide clear labels that describe the state being toggled
- Simple labels: `<Switch>Label text</Switch>`
- Complex labels: `<Switch><Switch.Label>Complex content</Switch.Label></Switch>`
- Consider using tooltips for additional context when needed
Best Practices:
- Always provide a visible label (string or `<Switch.Label>`)
- Use simple string children for basic labels
- Use `<Switch.Label>` for labels with formatting or complex content
- Make the toggle action and its effect immediately apparent
- Choose appropriate size and variant based on context
medium
small
DisabledEnabledFocused
accentdefaultoutline
small
DisabledEnabledFocused
accentdefaultoutline
Sizes
The `size` prop is used to set the size of the switch.
- `small`: height: 1rem / 16px
- `medium`: height: 1.5rem / 24px (default)
Variants
The `variant` prop is used to set the variant of the switch.
- `default`: The default variant of the switch.
- `accent`: The accent variant of the switch.
- `outline`: The outline variant of the switch.
Disabled
The `disabled` prop is used to disable the switch.
- `true`: The switch is disabled.
- `false`: The switch is enabled.
Label Usage
Label Usage: Demonstrates two ways to use labels with Switch.
- Simple string children: automatically wrapped with Switch.Label
- Explicit Switch.Label: for more complex label content
Simple string label (auto-wrapped):
Explicit Switch.Label (for complex content):
Legacy Label Prop
Legacy Label Prop: Shows backward compatibility with the label prop.
Note: The label prop is still supported for backward compatibility,
but using children is now the preferred approach.
With Tooltip
The Switch component does not have a built-in tooltip interface and requires the use of the `Tooltip` component to implement it.
API reference
| Switch.Label | Type | Default |
|---|---|---|
className | string |undefined | - |
| SwitchProps | Type | Default |
className | string |undefined | - |
focused | boolean |undefined | - |
label | string |undefined | - |
onChange | (value: boolean) => void | - |
readOnly | boolean |undefined | - |
size | undefined |"small" |"medium" | - |
value | boolean | - |
variant | undefined |"default" |"accent" |"outline" | - |