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 switchyarn nimbus-docs add switchpnpm nimbus-docs add switchbunx @cloudflare/nimbus-docs add switchPreview
<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">witharia-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.
| Prop | Type |
|---|---|
checked | boolean |
size | "sm" | "base" | "lg" |
disabled | boolean |