Toggle
The Toggle component, commonly referred to as a switch, 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.
This component is built on a native checkbox input and styled using Tailwind CSS. It supports labels, multiple sizes, controlled and uncontrolled usage, and full keyboard and screen reader accessibility.
Installation
Install the component using the Tailgrids CLI.
npx @tailgrids/cli add toggleUsage
import { Toggle } from "@/registry/core/toggle";
export default function ToggleBasic() {
return <Toggle label="Enable Feature X" defaultChecked />;
}Examples
Sizes
The toggle switch comes in sm and md sizes. The default size is sm.
Note: The size prop adjusts the dimensions of the track and the thumb for both sm and md sizes.
Label
The label is optional. When omitted, provide an accessible name using aria-label.
Controlled State
Use the checked and onChange props to fully control the toggle state.
Note:
Visual state is handled using CSS peer and peer-checked utilities. The primary color is applied to the background of the track when the switch is checked (peer-checked:bg-primary-500). The thumb position animates based on the checked state.
API Reference
Toggle
Extends input element props.
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | - | Optional text label displayed next to the switch. |
size | 'sm', 'md' | 'sm' | The size of the toggle switch. |
className | string | - | Additional CSS classes for the hidden input element (use standard HTML props for the overall control). |
Accessibility
- Built on a standard HTML
<input type="checkbox">which provides native keyboard and accessibility support. - Toggle the switch using the Space key when the component is focused.
- Visible label is properly associated via
htmlForandid - Input is visually hidden using
sr-onlybut remains available to screen readers - Works correctly with assistive technologies and form semantics
Note: This component is designed for use inside forms, settings pages, and preference panels.