Switch

An on/off switch on a <span role=switch> with a hidden native input beside it for forms. The thumb slides with a spring-eased CSS transition.

WAI-ARIA pattern

Installation

npx nuecrea-ui add switch

Usage

import * as Field from '@/components/ui/field';
import * as Switch from '@/components/ui/switch';

const label = 'flex items-center gap-2 text-sm';

export default function SwitchStory() {
  return (
    <main className="grid max-w-sm gap-4">
      <label className={label}>
        <Switch.Root>
          <Switch.Thumb />
        </Switch.Root>
        Airplane mode
      </label>
      <label className={label}>
        <Switch.Root defaultChecked>
          <Switch.Thumb />
        </Switch.Root>
        Wi-Fi
      </label>
      <label className={label}>
        <Switch.Root disabled readOnly defaultChecked>
          <Switch.Thumb />
        </Switch.Root>
        Managed by your admin
      </label>
      <Field.Root validationMode="onChange">
        <Field.Label className={label}>
          <Switch.Root name="backups" required>
            <Switch.Thumb />
          </Switch.Root>
          Enable backups
        </Field.Label>
        <Field.Error match="valueMissing">Backups must be on.</Field.Error>
      </Field.Root>
    </main>
  );
}

API reference

Switch.Root

The switch. Labelled by a wrapping <label> or a Field.Label. Renders <span> with role switch.

PropTypeDefaultDescription
checkedboolean—Controlled checked state.
defaultCheckedbooleanfalseInitial checked state when uncontrolled.
namestring—Name of the hidden input for form submission.
valuestring—Value of the hidden input when checked.
disabledbooleanfalseIgnores interaction and is removed from the tab order.
readOnlybooleanfalseFocusable but cannot be toggled.
requiredbooleanfalseMust be checked for the form/field to be valid (valueMissing).
EventPayloadDescription
onCheckedChangebooleanFired when the user toggles the switch. Angular: the `checked` model's change event.
Data attributePresent when
data-checkedchecked
data-uncheckednot checked
data-disableddisabled
data-readonlyread-only
data-requiredrequired
data-validin a Field: validated and valid
data-invalidin a Field: validated and invalid
data-dirtyin a Field: checked state differs from initial
data-touchedin a Field: has been blurred
data-filledin a Field: checked
data-focusedin a Field: focused

Switch.Thumb

The sliding knob. Always rendered. Renders <span>.

Data attributePresent when
data-checkedchecked
data-uncheckednot checked
data-disableddisabled
data-readonlyread-only
data-requiredrequired
data-validin a Field: validated and valid
data-invalidin a Field: validated and invalid
data-dirtyin a Field: checked state differs from initial
data-touchedin a Field: has been blurred
data-filledin a Field: checked
data-focusedin a Field: focused

Keyboard

KeyAction
SpaceToggles the switch.
EnterToggles the switch.