Skip to Content

Switch

A binary on/off control with role="switch".

Anatomy

import { Switch } from "@spacing-ui/core"; <Switch defaultChecked onCheckedChange={(c) => console.log(c)}> <span>Wi-Fi</span> </Switch>;

API

PropTypeDefaultDescription
checked / defaultCheckedbooleanfalse
onCheckedChange(checked: boolean) => void
disabledbooleanfalse

Accessibility

  • role="switch", aria-checked="true" or "false"
  • Space and Enter toggle
  • Disabled state via aria-disabled and disabled

Examples

Persisted preference

const [wifi, setWifi] = useLocalStorage("wifi", true); <Switch checked={wifi} onCheckedChange={setWifi}>Wi-Fi</Switch>

State-driven styling works via data-state="checked" / "unchecked".

Native form submission

<form action="/prefs" method="post"> <Switch name="notifications" defaultChecked>Notifications</Switch> <button type="submit">Save</button> </form>

Renders a hidden input with the given name so the switch value flows through FormData.

Live demo

Testing

const sw = screen.getByRole("switch", { name: /wi-fi/i }); expect(sw).toHaveAttribute("aria-checked", "true"); await userEvent.click(sw); expect(sw).toHaveAttribute("aria-checked", "false");
Last updated on