Skip to content

Switch

On/off control for a setting that applies at once.

Installation

Included in the starter. Every new site has it in src/components/ui/switch/. Import it where you need it, or register it in src/components.ts to use it on every page. If your site predates it, install it:

npx @cloudflare/nimbus-docs add switch

Preview

<Switch checked>Email notifications</Switch>

Examples

States

Off, on and disabled. The label is the slotted content, inside the same button, so clicking it flips the switch.

<Switch>Off</Switch>
<Switch checked>On</Switch>
<Switch disabled>Disabled</Switch>

Sizes

<Switch size="sm" checked>Small</Switch>
<Switch checked>Base</Switch>
<Switch size="lg" checked>Large</Switch>

React to a change

A click flips aria-checked and fires a bubbling change event. A script that owns the state elsewhere sets aria-checked itself.

<Switch id="compact-mode">Compact mode</Switch>

<script>
  const toggle = document.getElementById("compact-mode")!;
  toggle.addEventListener("change", () => {
    document.documentElement.dataset.compact = toggle.getAttribute("aria-checked")!;
  });
</script>

Accessibility

  • It’s a <button role="switch"> with aria-checked, so screen readers announce “switch, on” or “switch, off”.
  • Space and Enter flip it, as with any button.
  • Without a visible label, give it an aria-label.

API reference

Every prop the component accepts, sourced from a single declaration.

PropType
checked
boolean
size
"sm" | "base" | "lg"
disabled
boolean

Type to search…

↑↓ navigate↵ selectEsc close