Switch
The Switch component allows users to turn a setting on or off. It represents a binary choice and is typically used for preferences, feature flags, and configuration options.
It is built with React Aria Components Switch, styled with Tailwind CSS and the Tailgrids theme tokens, and supports labels, two sizes, two visual variants, controlled and uncontrolled usage, and full keyboard and screen reader accessibility.
Installation
Install the component using the Tailgrids CLI.
npx @tailgrids/cli@latest add switchUsage
import { Switch } from "@/components/tailgrids/switch";
export default function SwitchBasic() {
return <Switch defaultSelected>Enable Feature X</Switch>;
}Examples
Sizes
The switch comes in sm and default sizes. The default size is sm.
Variants
variant="default" is the standard switch. variant="new" is a Tailgrids variant with the thumb inset into a pill track.
Label
The label is the switch's children. When omitted, provide an accessible name using aria-label.
Controlled State
Use isSelected and onChange to control the switch. onChange receives the new boolean value.
Dark mode is off
API Reference
Switch
Extends React Aria's Switch props.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | 'default' | 'new' | 'default' | The visual style of the switch. |
size | 'sm' | 'default' | 'sm' | The size of the track and thumb. |
children | ReactNode | - | The label displayed next to the switch. |
isSelected | boolean | - | The controlled state. |
defaultSelected | boolean | - | The initial state when uncontrolled. |
onChange | (isSelected: boolean) => void | - | Called with the new state when it changes. |
isDisabled | boolean | false | Disables the switch. |
isReadOnly | boolean | false | Makes the switch read-only. |
className | string | - | Additional CSS classes for the root element. |
Accessibility
- Built on React Aria's
Switch, which renders a visually hidden<input type="checkbox" role="switch">. - Toggle the switch using the Space key when it is focused.
- The visible label is associated automatically; without one, pass
aria-label. - Focus, hover, disabled and invalid states are exposed as data attributes and styled with the theme tokens.
