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.

Small Size (sm)

Medium Size (md)

Controlled Example

Installation

Usage

import { Toggle } from "@/registry/core/toggle";

export default () => <Toggle label="Enable Feature X" defaultChecked />;

Examples

Small Size

The default size for the toggle switch is sm.

<Toggle label="Small Switch" size="sm" defaultChecked />

Medium Size

Use the md size for better visibility and improved touch targets.

<Toggle label="Medium Switch" size="md" />

Without Label

The label is optional. When omitted, provide an accessible name using aria-label.

<Toggle aria-label="Dark Mode Toggle" defaultChecked />

Controlled State

Use the checked and onChange props to fully control the toggle state.

const [isDark, setIsDark] = React.useState(false);

const handleChange = e => {
  setIsDark(e.target.checked);
};

return (
  <Toggle
    label="Dark Mode"
    checked={isDark}
    onChange={handleChange}
    size="md"
  />
);

API Reference

Toggle

Extends input element props (excluding size).

PropTypeDefaultDescription
labelstring-Optional text label displayed next to the switch.
size'sm', 'md''sm'The size of the toggle switch.
classNamestring-Additional CSS classes for the hidden input element (use standard HTML props for the overall control).
...inputPropsComponentProps<'input'>-All standard HTML <input> attributes, such as defaultChecked, checked, onChange, disabled, etc.

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 htmlFor and id
  • Input is visually hidden using sr-only but remains available to screen readers
  • Works correctly with assistive technologies and form semantics

Notes

  • 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
  • The size prop adjusts the dimensions of the track and the thumb for both 'sm' and 'md' sizes.
  • Designed for use inside forms, settings pages, and preference panels