<!-- index: /slotted/llms.txt -->
# switch

`data-ui="switch"` · Toggle that turns a setting on or off.

## Import

```tsx
import { Switch, SwitchDefaultsProvider } from '@slotted/react';
```

## Minimal example

Example

```tsx
import { Switch } from '@slotted/react/switch';

export default function SwitchBasic() {
  return (
    <Switch
      defaultChecked
      labelPlacement="start"
      name="lowStockAlerts"
      description="Email the buyer when a product falls below its reorder point."
    >
      Low-stock alerts
    </Switch>
  );
}
```

## Anatomy

| Part | Element | Required |
| --- | --- | --- |
| `root` | span, or the element render returns | yes |
| `control` | input[type=checkbox][role=switch] | yes |
| `track` | span | yes |
| `thumb` | span | yes |
| `label` | label | no |
| `description` | p | no |

## Props

| Name | Type | Default | Applies to | Description |
| --- | --- | --- | --- | --- |
| `checked` | `boolean` | — | Switch | The state, owned by the consumer for the life of the component when it is set. Unset, the element owns the state and a native form reset restores it. |
| `defaultChecked` | `boolean` | false | Switch | The state an uncontrolled switch starts from, read once and written to the element as the native attribute. |
| `children` | `ReactNode` | — | Switch | The label, beside the pill. It renders a label element pointing at the control through for, so it names the switch and a press on it toggles the switch. |
| `description` | `ReactNode` | — | Switch | Help text under the label and outside it. It reaches the control through aria-describedby, so it describes the switch and does not name it. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Switch, SwitchDefaultsProvider | The control step. A field around the switch decides it first, then the defaults provider. The pill, the thumb, the check and the label read the control scales, which the theme restates per density. |
| `indicator` | `'mark' \| 'none'` | mark | Switch, SwitchDefaultsProvider | What the thumb carries. mark draws a check when the switch is on and nothing when it is off. none draws nothing, and is correct only where text beside the switch states the value. |
| `labelPlacement` | `'end' \| 'start'` | end | Switch, SwitchDefaultsProvider | Which side of the label the pill sits on. start is the settings row: the label takes the free width and the pill sits at the end of the row. |
| `variant` | `'plain' \| 'control'` | plain | Switch, SwitchDefaultsProvider | control stands the switch in a box one control tall, so in a row of fields aligned to their end the pill sits on the line of their controls. --slotted-switch-control-block-size names another step than the switch size |
| `loading` | `boolean` | false | Switch | The value is not settled yet. The switch refuses every press, keeps its size, sets aria-busy, draws the morphing shape of Loader in the place of the thumb, and announces the pending label politely once the wait passes two seconds. |
| `loadingDelay` | `number` | 0 | Switch, SwitchDefaultsProvider | Milliseconds before the shape appears, so a write that answers sooner draws nothing. The switch refuses a press and sets aria-busy from the start of the wait, and keeps its mark and its cursor until the delay has passed. |
| `messages` | `Partial<SwitchMessages>` | — | Switch | Words that replace the active language’s, key by key: loading is what a screen reader hears while the switch is pending. The words reach a live region, not the control’s name, so the name never changes with the state. |
| `disabled` | `boolean` | from the field, or false | Switch | Unset rather than false, so the switch follows the field around it. A stated value wins. It is the native attribute, which takes the switch out of the tab order and out of form submission. |
| `readOnly` | `boolean` | from the field, or false | Switch | Unset rather than false. The native readonly attribute does nothing on a checkbox, so the switch sets aria-readonly and refuses every press. It stays focusable, announced and submitted. |
| `invalid` | `boolean` | from the field, or false | Switch | Unset rather than false, so the switch follows the field around it. Writes aria-invalid on the control and data-invalid on the root, which draws the edge and the focus ring in the danger tone. |
| `required` | `boolean` | — | Switch | The element’s own attribute, passed through unchanged; the switch never writes it. A required field sets aria-required instead, because the native attribute turns on browser constraint validation. |
| `name / value / form` | `string` | — / on / — | Switch | The element’s own attributes. The form submits name with value when the switch is on, and nothing when it is off, as it does for a checkbox. |
| `render` | `(props: SwitchRootProps) => ReactNode` | — | Switch | Replaces the root element and hands it every attribute. The props are typed against HTMLAttributes<HTMLElement>, so they can be spread onto a list item or a table cell. The control, the pill and the label are fixed: the control holds the state and the identifier, and the other parts are the switch’s own drawing. |
| `ref` | `Ref<HTMLInputElement>` | — | Switch | Reaches the control. focus() and click() are the element’s own, and a click() reaches onCheckedChange with the reason "programmatic". |
| `className / style` | `string / CSSProperties` | — | Switch | Reach the root, the element a consumer styles. Every other native prop reaches the control. |
| `SwitchDefaultsProvider` | `{ size, indicator, labelPlacement, loadingDelay, variant }` | — | a subtree | Sets size, indicator and labelPlacement once for every switch under it. A field outranks the provider’s size, so a switch inside a field takes the field’s step. |
| `useField()` | `() => FieldContextValue \| undefined` | — | inside a Field | What the switch reads from a field around it: the identifier, the description, and the disabled, read-only, invalid and required states. The switch needs no wiring inside a field. |

## Events

| Name | Payload | When |
| --- | --- | --- |
| `onCheckedChange` | `(checked: boolean, request: ChangeRequest<boolean>)` | Before the switch moves. request.value is the new state and request.previous the state it replaces. request.reason is "pointer" for a press, "keyboard" for Space or "programmatic" for element.click(). request.source is the originating event, and request.cancel() refuses the move before anything commits. |
| `onClick, onChange, onFocus, onBlur` | `the element’s own events` | Whenever the element fires them. The switch runs a consumer’s handler before its own, and a click handler that calls preventDefault() refuses the move before onCheckedChange is called. |

## Axes and defaults

| Axis | Values | Default |
| --- | --- | --- |
| `size` | `sm`, `md`, `lg` | `md` |
| `indicator` | `mark`, `none` | `mark` |
| `labelPlacement` | `end`, `start` | `end` |
| `variant` | `plain`, `control` | `plain` |

## Rules

- The pattern is the Switch of the WAI-ARIA Authoring Practices, built as the third of its reference implementations: an input[type=checkbox] with role="switch". The platform supplies the rest: Space toggles it, the label names it and toggles it, name and value are submitted, form.reset() restores it, and a disabled fieldset disables it.
- The switch writes no aria-checked. The Authoring Practices state that a switch built on a checkbox uses the HTML checked state instead, and writing both would state the value twice in two places that can disagree.
- Enter does not toggle the switch. The Authoring Practices list Enter as optional, and inside a form Enter submits the form, which a switch bound to Enter would prevent. A reader who expects Enter presses Space.
- The root carries no role, because ARIA makes the children of a switch presentational: the label and the description would otherwise join the control’s accessible name. The name of a switch does not change with its state, so the pending label is a live region and not part of the name.
- A required field sets aria-required, never the native required, which would turn on browser constraint validation and change how the form submits; a consumer who wants the native attribute writes required and it reaches the control. disabled is the native attribute. Read-only is aria-readonly plus a refused press, because the native readonly attribute does nothing on a checkbox.
- The target is at least 24 CSS pixels in both axes at every size and every density, as WCAG 2.2 success criterion 2.5.8 requires. The label supplies the height when there is one, and a switch without a label sets the minimum on its own row.
- The description sits outside the label, so it describes the switch and does not name it, and a press on it changes nothing.

## Tokens

`--slotted-control-border-color`, `--slotted-control-border-width`, `--slotted-control-font-family`, `--slotted-control-font-size-lg`, `--slotted-control-font-size-md`, `--slotted-control-font-size-sm`, `--slotted-control-height-lg`, `--slotted-control-height-md`, `--slotted-control-height-sm`, `--slotted-control-icon-size-lg`, `--slotted-control-icon-size-md`, `--slotted-control-icon-size-sm`, `--slotted-control-invalid-edge-width`, `--slotted-control-label-gap-lg`, `--slotted-control-label-gap-md`, `--slotted-control-label-gap-sm`, `--slotted-control-shadow`, `--slotted-control-transition-duration`, `--slotted-control-transition-easing`, `--slotted-disabled-background`, `--slotted-disabled-border`, `--slotted-disabled-foreground`, `--slotted-duration-loop-slow`, `--slotted-easing-emphasized`, `--slotted-focus-ring-color`, `--slotted-focus-ring-color-invalid`, `--slotted-focus-ring-offset`, `--slotted-focus-ring-width`, `--slotted-font-size-xs`, `--slotted-line-height-md`, `--slotted-line-height-xs`, `--slotted-radius-full`, `--slotted-space-1`, `--slotted-space-3`, `--slotted-surface`, `--slotted-switch-active-background`, `--slotted-switch-border-color`, `--slotted-switch-checked-active-background`, `--slotted-switch-checked-background`, `--slotted-switch-checked-border-color`, `--slotted-switch-checked-hover-background`, `--slotted-switch-checked-thumb-border-color`, `--slotted-switch-color`, `--slotted-switch-control-block-size`, `--slotted-switch-description-color`, `--slotted-switch-description-font-size`, `--slotted-switch-disabled-background`, `--slotted-switch-disabled-border-color`, `--slotted-switch-disabled-color`, `--slotted-switch-disabled-mark-color`, `--slotted-switch-disabled-thumb-background`, `--slotted-switch-hover-background`, `--slotted-switch-invalid-border-color`, `--slotted-switch-invalid-edge-width`, `--slotted-switch-invalid-focus-ring-color`, `--slotted-switch-line-height`, `--slotted-switch-mark-color`, `--slotted-switch-pending-color`, `--slotted-switch-radius`, `--slotted-switch-readonly-background`, `--slotted-switch-readonly-border-color`, `--slotted-switch-thumb-background`, `--slotted-switch-thumb-border-color`, `--slotted-switch-thumb-shadow`, `--slotted-switch-track-background`, `--slotted-switch-track-inline-size`, `--slotted-target-min`, `--slotted-text`, `--slotted-text-muted`, `--slotted-tone-accent-on-solid`, `--slotted-tone-accent-solid`, `--slotted-tone-accent-solid-active`, `--slotted-tone-accent-solid-hover`, `--slotted-tone-danger-border`, `--slotted-tone-secondary-solid`, `--slotted-tone-secondary-solid-active`, `--slotted-tone-secondary-solid-hover`

## Examples

### Playground

One switch with every axis on it, driven by the controls below the canvas. Click the label as well as the pill: the label names the control and doubles its target.

Excerpt — not a complete module

```tsx
<Switch
  defaultChecked
  description="The invoice is charged on the 5th of each month."
  name="autopay"
>
  Autopay
</Switch>;
```

### The step the control sits at

Three steps, and inside a field the switch takes the field’s rather than its own: a small field holding a medium control is a field and a control disagreeing about one row.

Example

```tsx
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchSizes() {
  return (
    <Stack gap={4}>
      <Switch size="sm" defaultChecked>
        Show archived orders
      </Switch>
      <Switch size="md" defaultChecked>
        Group orders by warehouse
      </Switch>
      <Switch size="lg" defaultChecked>
        Print packing slips
      </Switch>
    </Stack>
  );
}
```

### The mark inside the thumb

On draws a check and off draws nothing, so the state is readable without color and without comparing the thumb’s position to a switch you cannot see.

Example

```tsx
import { useState } from 'react';
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchIndicator() {
  const [open, setOpen] = useState(true);

  return (
    <Stack gap={5}>
      <Switch defaultChecked>Accept backorders</Switch>
      <Switch
        checked={open}
        indicator="none"
        onCheckedChange={setOpen}
        description={
          open ? 'Open: customers can place orders.' : 'Closed: customers see a maintenance page.'
        }
      >
        Storefront
      </Switch>
    </Stack>
  );
}
```

### Which side the pill sits on

start is the settings row every product writes: the label takes the free width, the pill sits at the end, and a column of rows ends with every pill at the same distance from the edge.

Example

```tsx
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchPlacement() {
  return (
    <Stack gap={5}>
      <Switch defaultChecked description="Paid invoices arrive as PDF attachments.">
        Email me a copy of each invoice
      </Switch>
      <Switch labelPlacement="start" description="Unpaid invoices are flagged on the 5th day.">
        Overdue reminders
      </Switch>
    </Stack>
  );
}
```

### Help text under the label

It sits outside the label, so it describes the switch rather than naming it — and so a paragraph of help text does not change a setting when it is clicked.

Excerpt — not a complete module

```tsx
<Switch defaultChecked description="The invoice is charged on the 5th of each month.">
  Autopay
</Switch>;
```

### The states the pill paints

Read-only goes hollow and keeps its color, because the value is real and still submitted; disabled goes grey and its knob goes with it, so a locked setting still says which way it is set.

Example

```tsx
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchStates() {
  return (
    <Stack gap={5}>
      <Switch defaultChecked readOnly description="Your organization's security policy sets this.">
        Two-step sign-in
      </Switch>
      <Switch defaultChecked disabled description="Included in the Business plan.">
        Audit log
      </Switch>
      <Switch disabled description="Available on the Enterprise plan.">
        Single sign-on
      </Switch>
    </Stack>
  );
}
```

### A setting that has not landed yet

The thumb becomes the morphing shape of Loader, its mark gone, and the pill keeps its size so the row does not move. A second press is refused before the DOM can show a state the server does not have. loadingDelay holds the shape back while a write answers fast.

Example

```tsx
import { useState } from 'react';
import { Switch } from '@slotted/react/switch';

/** Stands in for the request that stores the setting. */
const saveSetting = (on: boolean) =>
  new Promise<boolean>((resolve) => setTimeout(() => resolve(on), 2500));

export default function SwitchLoading() {
  const [syncing, setSyncing] = useState(false);
  const [saving, setSaving] = useState(false);

  const change = async (next: boolean) => {
    setSaving(true);
    setSyncing(await saveSetting(next));
    setSaving(false);
  };

  return (
    <Switch
      checked={syncing}
      labelPlacement="start"
      loading={saving}
      messages={{ loading: 'Saving order sync' }}
      onCheckedChange={change}
      description="Imports new Shopify orders every five minutes."
    >
      Order sync
    </Switch>
  );
}
```

### Inside a field

The switch takes the identifier, the description, the error and the four shared states without being asked, and it writes aria-required rather than the native attribute.

Example

```tsx
import { Field, FieldDescription, FieldError, FieldLabel } from '@slotted/react/field';
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchField() {
  return (
    <Stack gap={5}>
      <Field>
        <FieldLabel>Backorders</FieldLabel>
        <Switch>Accept orders when an item is out of stock</Switch>
        <FieldDescription>Customers see the restock date at checkout.</FieldDescription>
      </Field>
      <Field invalid>
        <FieldLabel>Sales tax</FieldLabel>
        <Switch defaultChecked>Collect tax on orders shipped to Nevada</Switch>
        <FieldError>Add a Nevada tax ID before collecting tax there.</FieldError>
      </Field>
    </Stack>
  );
}
```

### A row on a settings page

Where a switch actually lives: the label takes the free width, the pill sits at the end of the row, and the description sits under the label rather than under the pill.

Example

```tsx
import { Card, CardBody, CardHeader } from '@slotted/react/card';
import { Divider } from '@slotted/react/divider';
import { Stack } from '@slotted/react/stack';
import { Switch, SwitchDefaultsProvider } from '@slotted/react/switch';
import { Heading, Text } from '@slotted/react/typography';

export default function SwitchSettings() {
  return (
    <Card>
      <CardHeader>
        <Heading level={3} size="md">
          Warehouse notifications
        </Heading>
        <Text size="sm" tone="muted">
          Sent to ops@northwind.example.
        </Text>
      </CardHeader>
      <CardBody>
        <SwitchDefaultsProvider labelPlacement="start">
          <Stack gap={4}>
            <Switch defaultChecked description="When a product falls below its reorder point.">
              Low stock
            </Switch>
            <Divider />
            <Switch defaultChecked description="When a carrier misses its pickup window.">
              Late pickups
            </Switch>
            <Divider />
            <Switch description="When a count differs from the system by more than 2%.">
              Cycle count variances
            </Switch>
          </Stack>
        </SwitchDefaultsProvider>
      </CardBody>
    </Card>
  );
}
```

### What a consumer can replace

The root becomes any element render returns, an application sets the family’s defaults once, and every native attribute a consumer writes lands on the control rather than on the box.

Excerpt — not a complete module

```tsx
<SwitchDefaultsProvider labelPlacement="start" size="sm">
  <Switch>Alertas por e-mail</Switch>
</SwitchDefaultsProvider>;

// The root becomes a list item, so a settings list is a list.
<Switch render={(props) => <li {...props} />}>Resumo semanal</Switch>;
```

### The keyboard

Tab reaches the control and Space toggles it, both from the platform. Enter is deliberately not bound: inside a form it submits, and a switch that stole it would break the form.

Excerpt — not a complete module

```tsx
<Switch
  onCheckedChange={(next, request) => {
    // "pointer", "keyboard" or "programmatic".
    if (request.reason === 'pointer' && next) request.cancel();
  }}
>
  Receive the invoice
</Switch>;
```

### controlled.tsx

Example

```tsx
import { useState } from 'react';
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';

export default function SwitchControlled() {
  const [paused, setPaused] = useState(false);

  return (
    <Stack gap={5}>
      <Switch
        checked={paused}
        labelPlacement="start"
        onCheckedChange={setPaused}
        description="Turns off the alerts below until you resume."
      >
        Pause all alerts
      </Switch>
      <Stack gap={4}>
        <Switch defaultChecked disabled={paused} labelPlacement="start">
          New orders
        </Switch>
        <Switch defaultChecked disabled={paused} labelPlacement="start">
          Failed payments
        </Switch>
        <Switch disabled={paused} labelPlacement="start">
          Return requests
        </Switch>
      </Stack>
    </Stack>
  );
}
```

### form.tsx

Example

```tsx
import { useState } from 'react';
import type { SubmitEvent } from 'react';
import { Button } from '@slotted/react/button';
import { Inline } from '@slotted/react/inline';
import { Stack } from '@slotted/react/stack';
import { Switch } from '@slotted/react/switch';
import { Text } from '@slotted/react/typography';

export default function SwitchForm() {
  const [submitted, setSubmitted] = useState<string | null>(null);

  const submit = (event: SubmitEvent<HTMLFormElement>) => {
    event.preventDefault();
    const names = [...new FormData(event.currentTarget).keys()];
    setSubmitted(names.length > 0 ? names.join(', ') : 'nothing');
  };

  return (
    <form onSubmit={submit} onReset={() => setSubmitted(null)}>
      <Stack gap={4}>
        <Switch name="dailySummary" defaultChecked labelPlacement="start">
          Daily sales summary
        </Switch>
        <Switch name="weeklyForecast" labelPlacement="start">
          Weekly demand forecast
        </Switch>
        <Switch name="supplierDelays" defaultChecked labelPlacement="start">
          Supplier delay report
        </Switch>
        <Inline gap={3} align="center">
          <Button type="submit">Save</Button>
          <Button type="reset" tone="secondary" variant="outline">
            Reset
          </Button>
          {submitted && (
            <Text size="sm" tone="muted">
              Submitted {submitted}
            </Text>
          )}
        </Inline>
      </Stack>
    </form>
  );
}
```
