# Switch

A toggle control for a binary setting.

- Category: Core Elements
- Page: https://wunderui.com/components/switch
- Tier: Free

## Install

```bash
npx wunderui-cli add switch
```

## Import

```tsx
import { Switch, SwitchItemCell } from "@/components/ui/switch"
```

## Minimal usage

Then use it:

```tsx
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function Notifications() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" defaultChecked />
      <Label htmlFor="notifications">Email notifications</Label>
    </div>
  )
}
```

Expected result: You see one small switch, turned on, with the label Email notifications. A click on the switch or the text turns it off.

## Usage

```tsx
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" />
      <Label htmlFor="notifications">Email notifications</Label>
    </div>
  )
}
```

## When to use

### Use Switch for

- One setting that is on or off and takes effect at once, such as notifications
- A row of settings, each with a title and a short description
- A master switch that turns a group of settings on or off

### Use something else

- [Checkbox](https://wunderui.com/components/checkbox) for a choice that is saved later with a form, or several choices from a list
- [Radio Group](https://wunderui.com/components/radio-group) for one choice out of several named options
- [Segment](https://wunderui.com/components/segment) for switching between views, with one always selected
- [Selector Item](https://wunderui.com/components/selector-item) for a whole row with a title, a description and a switch

## Keyboard

A switch is one tab stop. It is a button in all but name, so Space and Enter both toggle it.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Moves focus to the next or previous switch in the order they are written. A disabled switch is skipped. |
| `Space` or `Enter` | Toggles the focused switch and calls `onCheckedChange`. A switch that is `saving` or `readOnly` ignores both keys. |

## Behavior

What the switch does itself, and what it leaves to the page.

- **Two elements, one control:** The visible track is a switch element, with a hidden checkbox input beside it that carries the name, value and form state. Labels are copied onto it so page checkers see a named input.
- **Controlled or not:** Pass a checked value and a change handler to own the value, or a default to let the switch keep it. There is no indeterminate state.
- **Names:** A Label linked to the switch names it and makes the text a click target. Inside a Selector Item the title names it, and otherwise you pass an aria-label.
- **Hit area:** The area that takes a click reaches 12 px to the sides and 8 px above and below the track, so a near miss still toggles it.
- **Hover and pressed:** An off track gets a rim on hover and a darker grey while pressed, and a brand track darkens on hover and again when pressed. Disabled is the rest look at 40 % opacity.
- **Saving:** Saving puts a spinner on the knob, marks the switch busy and makes it read-only until you clear it. Set the switch to its new value first, then clear saving when the request ends.
- **Save failed:** A failed save is not an invalid value, so the switch is not marked invalid. Set it back to its previous value and show a message with a retry next to it, as a Selector Item error does.
- **In a form:** With a name the switch submits its value (default on) when on, and nothing when off unless you set an unchecked value. Required asks for it to be on before the form is sent.
- **Motion:** The track changes colour quickly and the knob slides with an overshoot, swinging slightly past the end and settling. A second click reverses it from wherever it is.
- **Reduced motion:** With reduced motion the knob no longer slides but jumps to the other end, the colour change stays, and the spinner stays as a still glyph.

## Anatomy

- `Switch`: The track, with the switch role: 32 by 18 px by default, 24 by 14 px small. Grey when off, brand, neutral or muted when on, with a hit area that reaches 12 px sideways and 8 px up and down.
- `Thumb`: The round knob, which slides with a slight overshoot and reverses mid-way if clicked again. While saving it shows a spinner, and Switch renders it for you.
- `Label`: The text that names the setting, a Label linked to the switch or the title of a Selector Item, and clicking it toggles the switch. Name the setting, never the state.
- `SwitchItemCell`: A table cell that puts a Switch and its text in one label, so the text also toggles it.
- `Spinner`

## Best practices

### When to use

- Use it for one setting that is on or off and takes effect at once, such as email notifications. For a choice that is saved later with a form, use a Checkbox.

### Do

- Give every switch a visible label and link it to the switch. A click on the text then toggles it, and a screen reader announces the name with on or off.
- Name the setting, not the state: Email notifications, not On. The switch role already tells screen readers whether it is on.
- Set the saving state while a request runs. The knob shows a spinner and clicks are ignored until the save ends.
- When a save fails, set the switch back to its previous value and say so in a message with a retry, like Couldn't save. Try again.
- Use the small size in dense rows such as table cells, and the default size in forms and settings.

### Don't

- Don't mark a switch invalid. It has no wrong value, and a failed save is an error of the request, so put it in the message.
- Don't use a Switch to choose between two named options such as Monthly and Yearly. That is a choice, not on or off, so use a Radio Group.
- Don't ask people to press a Save button after a Switch. A switch that waits for a button is a Checkbox.

## API reference

### Switch

| Prop | Type | Default | Description |
|---|---|---|---|
| appearance | "neutral" \| "brand" \| "muted" | "brand" | The colour of the track while it is on: `brand`, `neutral` (the inverse surface, black in light mode and white in dark mode) or `muted` (quiet grey). |
| checked | boolean |  | Whether the switch is on. Pass it together with `onCheckedChange` to control the switch; use `defaultChecked` to let the switch keep the value. |
| className | string \| ((state: State) => string \| undefined) |  | Extra classes, merged with the switch's own. A string, or a function of the state. Use it for spacing such as `mt-px`, not to recolour the track. |
| defaultChecked | boolean | false | Whether the switch starts on, when the switch keeps its own value. |
| disabled | boolean | false | The switch ignores clicks and keys, is dimmed to 40 % and is skipped by Tab. Dim the label yourself. |
| form | string |  | The id of the form that owns the hidden input, for a switch that is rendered outside the form. |
| id | string |  | The id of the hidden input. Point the `htmlFor` of the `Label` at it. |
| inputRef | React.Ref<HTMLInputElement> |  | A ref to the hidden `<input>`. The component also copies `aria-label` and `aria-labelledby` onto it. |
| name | string |  | The name of the field when a form is sent. |
| nativeButton | boolean | false | Set it to `true` when `render` swaps the element for a native `<button>`; the `id` then goes on that element. |
| onCheckedChange | (checked: boolean, eventDetails) => void |  | Called when the switch is turned on or off, with the new value as a boolean. |
| readOnly | boolean | false | The switch keeps its value and cannot be turned on or off. It is announced as read-only. |
| render | React.ReactElement \| ComponentRenderFn<RenderFunctionProps, State> |  | Replaces the element of the track with another tag or component. Accepts an element or a function that returns one. |
| required | boolean | false | The switch must be on before a form that holds it can be sent. It does not draw anything by itself. |
| saving | boolean | false | A save is running: the knob shows a spinner, the switch is `aria-busy` and ignores clicks and keys until you clear it. |
| size | "sm" \| "default" | "default" | `default` is 32 by 18 px, for forms and settings. `sm` is 24 by 14 px, for dense rows such as table cells. |
| style | React.CSSProperties \| ((state: State) => React.CSSProperties \| undefined) |  | Inline style for the track, an object or a function of the state. |
| uncheckedValue | string |  | The value sent with the form when the switch is off. By default an off switch sends nothing, like a native checkbox. |
| value | string |  | The value sent with the form when the switch is on. The default is `on`. |

Also accepts React.HTMLAttributes attributes.

### SwitchItemCell

| Prop | Type | Default | Description |
|---|---|---|---|
| checked | boolean |  | Whether the switch in the cell is on. |
| children | ReactNode |  | The text next to the switch. It is inside the same `<label>`, so a click on it toggles the switch. |
| onCheckedChange | (checked: boolean) => void |  | Called when the switch in the cell is turned on or off. |

## Examples

### Appearance: brand, neutral and muted

```tsx
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" defaultChecked />
      <Label htmlFor="notifications">Email notifications</Label>
    </div>
  )
}
```

### Sizes: regular and small

```tsx
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" />
      <Label htmlFor="notifications">Email notifications</Label>
    </div>
  )
}
```

### States: default, disabled and saving

```tsx
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" />
      <Label htmlFor="notifications">
        Email notifications
      </Label>
    </div>
  )
}
```

### Label and description: before, after and as a row

```tsx
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" defaultChecked />
      <Label htmlFor="notifications">Email notifications</Label>
    </div>
  )
}
```

### Save failed: saving and a failed save

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

type Status = "idle" | "saving" | "saved" | "failed"

// A stand-in for your request: it takes a moment and succeeds.
function save() {
  return new Promise<void>((resolve) => window.setTimeout(resolve, 1200))
}

export function Example() {
  const [on, setOn] = useState(true)
  const [status, setStatus] = useState<Status>("idle")

  async function change(next: boolean) {
    setStatus("saving")
    setOn(next)
    try {
      await save()
      setStatus("saved")
    } catch {
      // The save failed: go back to the previous value and say so.
      setOn(!next)
      setStatus("failed")
    }
  }

  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center gap-2">
        <Switch id="sync" checked={on} onCheckedChange={change} saving={status === "saving"} />
        <Label htmlFor="sync">Email notifications</Label>
      </div>
      <div aria-live="polite" className="flex min-h-8 items-center gap-2 text-sm">
        {status === "saving" && <span className="text-text-secondary">Saving…</span>}
        {status === "saved" && <span className="text-text-secondary">Saved</span>}
        {status === "failed" && (
          <>
            <span className="text-text-error">Couldn&apos;t save. Try again.</span>
            <Button variant="plain" size="sm" onClick={() => change(!on)}>
              Retry
            </Button>
          </>
        )}
      </div>
    </div>
  )
}
```

## In context

### Notifications: a list with saving and save failed

Each switch takes effect at once. The second one fails on its first try, goes back to its previous state and offers a retry, which works.

```tsx
import { useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { SelectorItem, SelectorItemGroup } from "@/components/ui/selector-item"
import { Switch } from "@/components/ui/switch"

type Status = "idle" | "saving" | "failed"

const SETTINGS = [
  { id: "email", title: "Email notifications", description: "Receive updates about assigned tasks", fails: false },
  { id: "push", title: "Push notifications", description: "Alerts on your phone and desktop", fails: true },
  { id: "digest", title: "Weekly digest", description: "A summary of your projects every Monday", fails: false },
]

// A stand-in for your request: it takes a moment, and `fails` makes it fail.
function save(fails: boolean) {
  return new Promise<void>((resolve, reject) =>
    window.setTimeout(() => (fails ? reject(new Error("Save failed")) : resolve()), 1200)
  )
}

export function Example() {
  const [values, setValues] = useState<Record<string, boolean>>({ email: true, push: false, digest: true })
  const [status, setStatus] = useState<Record<string, Status>>({})
  const tries = useRef<Record<string, number>>({})

  async function change(id: string, next: boolean, fails: boolean) {
    const attempt = tries.current[id] ?? 0
    tries.current[id] = attempt + 1
    setStatus((current) => ({ ...current, [id]: "saving" }))
    setValues((current) => ({ ...current, [id]: next }))
    try {
      // A setting that fails does so on its first try only, so the retry works.
      await save(fails && attempt === 0)
      setStatus((current) => ({ ...current, [id]: "idle" }))
    } catch {
      // The switch goes back to its previous value and the row says why.
      setValues((current) => ({ ...current, [id]: !next }))
      setStatus((current) => ({ ...current, [id]: "failed" }))
    }
  }

  return (
    <SelectorItemGroup>
      {SETTINGS.map((setting) => {
        const failed = status[setting.id] === "failed"
        return (
          <SelectorItem
            key={setting.id}
            title={setting.title}
            description={setting.description}
            error={failed ? "Couldn't save. Try again." : undefined}
            announceError
            action={
              failed ? (
                <Button variant="plain" size="sm" onClick={() => change(setting.id, !values[setting.id], setting.fails)}>
                  Retry
                </Button>
              ) : undefined
            }
            control={
              <Switch
                checked={values[setting.id]}
                onCheckedChange={(next) => change(setting.id, next, setting.fails)}
                saving={status[setting.id] === "saving"}
                aria-invalid={false}
              />
            }
          />
        )
      })}
    </SelectorItemGroup>
  )
}
```

### Privacy: rows with an icon and a description

A Selector Item per setting: an icon tile, a title and a description on the left, the switch on the right.

```tsx
import { Eye, MapPin, ShieldCheck } from "lucide-react"
import { SelectorItem, SelectorItemGroup } from "@/components/ui/selector-item"
import { Switch } from "@/components/ui/switch"

const SETTINGS = [
  { id: "profile", icon: Eye, title: "Public profile", description: "Anyone with the link can see your profile", on: true },
  { id: "location", icon: MapPin, title: "Share location", description: "Show your city on your profile", on: false },
  { id: "two-step", icon: ShieldCheck, title: "Two-step sign-in", description: "Ask for a code on a new device", on: true },
]

export function Example() {
  return (
    <SelectorItemGroup>
      {SETTINGS.map((setting) => {
        const Icon = setting.icon
        return (
          <SelectorItem
            key={setting.id}
            leading={
              <span className="flex size-8 items-center justify-center rounded-md bg-tint-indigo text-tint-text-indigo [&_svg]:size-4">
                <Icon />
              </span>
            }
            title={setting.title}
            description={setting.description}
            control={<Switch defaultChecked={setting.on} />}
          />
        )
      })}
    </SelectorItemGroup>
  )
}
```

### Master switch: dependent settings

Turning the master switch off disables the switches below it. They keep their values, so turning it on again restores them.

```tsx
import { useState } from "react"
import { SelectorItem, SelectorItemGroup } from "@/components/ui/selector-item"
import { Switch } from "@/components/ui/switch"

export function Example() {
  const [all, setAll] = useState(true)

  return (
    <div className="flex flex-col gap-3">
      <SelectorItem
        title="Allow notifications"
        description="Turn this off to pause everything below"
        control={<Switch checked={all} onCheckedChange={setAll} />}
      />
      {/* The switches below keep their values, but cannot be changed while the master switch is off. */}
      <SelectorItemGroup>
        <SelectorItem title="Email" description="Updates about assigned tasks" control={<Switch defaultChecked disabled={!all} />} />
        <SelectorItem title="Push" description="Alerts on your phone and desktop" control={<Switch disabled={!all} />} />
        <SelectorItem title="Weekly digest" description="A summary every Monday" control={<Switch defaultChecked disabled={!all} />} />
      </SelectorItemGroup>
    </div>
  )
}
```

## For AI agents

`get_component("switch")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
