Skip to content

Fields

Switch

An on/off setting backed by a native checkbox.

When to use it: Use it for a setting that plainly means on or off.

On this page

Example

Switch.tsxtsx
import { Switch } from "@comp0/react";

export function Example() {
  return (
    <Switch
      className="group flex min-h-7 items-center gap-2 rounded px-1 text-base text-zinc-800 data-selected:bg-teal-50 data-selected:text-teal-950 sm:text-sm dark:text-zinc-100 dark:data-selected:bg-teal-950/40 dark:data-selected:text-teal-50"
      defaultChecked
      name="alerts"
    >
      <span className="h-6 w-11 shrink-0 rounded-full bg-zinc-200 p-0.5 ring-2 ring-transparent transition-colors duration-150 ease-out group-data-focused:ring-teal-600 group-data-selected:bg-teal-600 motion-reduce:transition-none sm:h-5 sm:w-9 dark:bg-zinc-800 dark:group-data-focused:ring-teal-400 dark:group-data-selected:bg-teal-400">
        <span className="block size-5 rounded-full bg-white shadow-sm transition-transform duration-150 ease-out group-data-selected:translate-x-5 motion-reduce:transition-none sm:size-4 sm:group-data-selected:translate-x-4 dark:shadow-none" />
      </span>
      Enable alerts
    </Switch>
  );
}

Anatomy

Dashed frames are invisible state providers; shaded shapes own real DOM. Numbered pins match the list below.

A wireframe sketch of the assembled component. Each numbered marker matches a part in the list that follows.

  1. Switch

    Label with a hidden native checkbox. Owns a DOM element.

Step by step

  1. 1

    Add the main part

    Add Switch beside its setting words.

  2. 2

    Add the supporting parts

    Choose defaultChecked when it needs a starting state.

  3. 3

    Make the behavior clear

    Give it a name if a form must send the setting.

    Exampletsx
    <Switch name="alerts">Email alerts</Switch>

Keyboard

Space
Changes the switch.

Forms and accessibility

A selected switch submits like a native checkbox.

Accessibility checklist

  • Label the setting, not merely the current state.
  • Make on and off understandable without color.
  • Use a checkbox instead when the choice belongs in a multi-select list.

API reference

Importtsx
import { Switch } from "@comp0/react";

Switch

DOM element

Label with a hidden native checkbox.

PropTypeDescription
namestringSubmission name for the setting.
checked / defaultCheckedbooleanControlled or initial on state.
onChange(selected: boolean) => voidReceives the next on state.
disabledbooleanDisables the switch.

Style hooks

Attributes that appear while a state is true. Target them with Tailwind data variants such as data-open:bg-zinc-100, or with any CSS selector.

[data-selected]

on Switch

The switch is on.
[data-disabled]

on Switch

The switch is disabled.

Keep exploring