Skip to content
Browse docs

Switch

Beta

An on and off toggle that submits with forms like a checkbox.

---
import Switch from "@/components/ui/switch/Switch.astro";
---

<Switch checked>Email notifications</Switch>

Installation

npx eris-ui@latest add switch
pnpm dlx eris-ui@latest add switch
bunx eris-ui@latest add switch
yarn dlx eris-ui@latest add switch

Installs @zag-js/switch, @zag-js/vanilla.

How it works

The switch is a real <input type="checkbox" role="switch"> inside a <label>, drawn with CSS. It toggles, shows its state and submits with a form before its script loads, and with JavaScript turned off. The script adds data-state, data-focus and data-hover attributes for styling.

States

---
import Switch from "@/components/ui/switch/Switch.astro";
---

<div class="flex flex-col items-start gap-4">
  <Switch disabled>Disabled</Switch>
  <Switch disabled checked>
    Disabled and on
  </Switch>
  <Switch readOnly checked>
    Read only
  </Switch>
  <Switch invalid>Invalid</Switch>
</div>

A readOnly switch keeps focus and is still sent with the form, but does not change. A disabled switch is skipped by Tab and left out of the form.

In a form

Give the switch a name. While it is on, the form sends that name with value, which defaults to on. While it is off, the form sends nothing for it. A form reset returns it to how it loaded.

---
import Switch from "@/components/ui/switch/Switch.astro";
import Button from "@/components/ui/button/Button.astro";
---

<form class="flex flex-col items-start gap-4">
  <Switch name="digest" value="weekly" checked>
    Weekly digest
  </Switch>
  <Switch name="beta">Beta features</Switch>
  <div class="flex gap-3">
    <Button type="submit" size="sm">
      Save
    </Button>
    <Button type="reset" size="sm" variant="secondary">
      Reset
    </Button>
  </div>
</form>

Without visible text

When a switch has no text next to it, name it with label so screen readers can announce it.

---
import Switch from "@/components/ui/switch/Switch.astro";
---

<Switch label="Airplane mode" />

Keyboard

Key Does
Tab Moves focus to the switch
Space Turns the switch on or off

Props

Prop Default Does
checked false On when the page loads
name Field name sent with the form
value "on" Value sent while the switch is on
disabled false Cannot be focused or changed, and is not submitted
readOnly false Can be focused and is submitted, but cannot be changed
required false The form will not submit while the switch is off
invalid false Marks the switch as failing validation
form Id of a form elsewhere on the page
label Accessible name when there is no visible text
id random Id for the instance, used to build the part ids