# Switch

Toggles a setting that applies immediately.

[View source and API](https://github.com/tempoxyz/ds/blob/main/src/web/components/Switch.tsx)

Figma: [Switch · Existing candidate](https://www.figma.com/design/yE96kcymnNR88PJp6G1sPs?node-id=1401-11548)

## Overview

A pill toggle whose thumb and track color both show the state.

## Examples

### Basic

```tsx
import { Switch } from '@tempoxyz/ds'

export function Demo() {
  return <Switch aria-label="Notifications" />
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Switch/Basic.tsx)

### Size

Set `size` to `small`, `medium`, or `large`. It defaults to `medium`, or `small` inside [ListGroup](/docs/components/list-group).

```tsx
import { style, Switch } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.row()}>
      {(['small', 'medium', 'large'] as const).map((size) => (
        <Switch aria-label={size} key={size} size={size} />
      ))}
    </div>
  )
}

namespace styles {
  export const row = style({ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '24' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Switch/Size.tsx)

### Checked

Set `defaultChecked`, or control the state with `checked` and `onCheckedChange`.

```tsx
import { style, Switch } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.row()}>
      {(['small', 'medium', 'large'] as const).map((size) => (
        <Switch aria-label={`${size} on`} defaultChecked key={size} size={size} />
      ))}
    </div>
  )
}

namespace styles {
  export const row = style({ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '24' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Switch/Checked.tsx)

### Disabled

Set `disabled` to block toggling.

```tsx
import { style, Switch } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.row()}>
      {(['small', 'medium', 'large'] as const).map((size) => (
        <Switch aria-label={`${size} disabled`} disabled key={size} size={size} />
      ))}
    </div>
  )
}

namespace styles {
  export const row = style({ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '24' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Switch/Disabled.tsx)

### Field

Place the switch in a `Field.Root` below its `Field.Label`, with the `Field.Description` under it.

```tsx
import { Field, style, Switch } from '@tempoxyz/ds'

export const fill = true
export function Demo() {
  return (
    <div {...styles.settings()}>
      <Field.Root>
        <Field.Label>Auto-convert</Field.Label>
        <Switch defaultChecked />
        <Field.Description>Swap incoming funds to USDC.</Field.Description>
      </Field.Root>
      <Field.Root>
        <Field.Label>Notifications</Field.Label>
        <Switch />
        <Field.Description>Email me when a payment settles.</Field.Description>
      </Field.Root>
    </div>
  )
}

namespace styles {
  export const settings = style({ display: 'grid', gap: '24', maxWidth: '480px !custom' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Switch/Field.tsx)

## Anatomy

Import the component and assemble its parts.

```tsx
import { Switch } from '@tempoxyz/ds'

<Switch />
```

## Guidelines

### When to Use

* Turn a setting on or off at once, such as payment emails, hiding small balances, or pausing a webhook.
* List independent settings on a settings page, one per row.

### When Not to Use

* Use a [Checkbox](/docs/components/checkbox) for a choice that applies on form submit, or for agreeing to terms.
* Use a [RadioGroup](/docs/components/radio-group) or [ChoiceGroup](/docs/components/choice-group) when the two states aren't on and off, such as Daily and Weekly.
* Use a [Button](/docs/components/button) for a one-time action, such as Revoke key.

### Apply the Change Immediately

Save the new state in `onCheckedChange`, not on a Save button.

**Do:** Save each setting the moment its switch flips.

```tsx
/**
 * Do example for "Apply the Change Immediately" on the Switch page.
 * Save each setting the moment its switch flips.
 * @module
 */
import { Field, Fieldset, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Fieldset.Root {...styles.settings()}>
      <Field.Root>
        <Field.Label>Payment emails</Field.Label>
        <Switch defaultChecked />
        <Field.Description>Email me when a payment settles.</Field.Description>
      </Field.Root>
      <Field.Root>
        <Field.Label>Hide small balances</Field.Label>
        <Switch />
        <Field.Description>Hide tokens worth under $1.</Field.Description>
      </Field.Root>
    </Fieldset.Root>
  )
}

namespace styles {
  export const settings = style({ maxWidth: '20rem !custom', rowGap: '0', width: '100% !custom' })
}
```

**Don't:** Add a Save button to a group of switches. Use a [Checkbox](/docs/components/checkbox) in a
form instead.

```tsx
/**
 * Don't example for "Apply the Change Immediately" on the Switch page.
 * Don't add a Save button to a group of switches. Use a Checkbox in a form instead.
 * @module
 */
import { Button, Field, Fieldset, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Fieldset.Root {...styles.settings()}>
        <Field.Root>
          <Field.Label>Payment emails</Field.Label>
          <Switch defaultChecked />
          <Field.Description>Email me when a payment settles.</Field.Description>
        </Field.Root>
        <Field.Root>
          <Field.Label>Hide small balances</Field.Label>
          <Switch />
          <Field.Description>Hide tokens worth under $1.</Field.Description>
        </Field.Root>
      </Fieldset.Root>
      <Button size="small">Save changes</Button>
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-end',
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    maxWidth: '20rem !custom',
    width: '100% !custom',
  })

  export const settings = style({ rowGap: '0', width: '100% !custom' })
}
```

* **Failed saves:** Update `checked` optimistically. If the save fails, flip it back and explain why in a [Toast](/docs/components/toast).
* **Risky changes:** If a change needs confirmation, costs money, or can't be undone, use a [Button](/docs/components/button) and an [AlertDialog](/docs/components/alert-dialog).
* **Delayed changes:** If a change takes a few seconds to apply, state it in the description, such as Applies to new payments.

### Name the Setting, Not the State

Don't write Enabled or Turn on, and don't change the label with the state.

**Do:** Label the setting the switch controls, such as Payment emails.

```tsx
/**
 * Do example for "Name the Setting, Not the State" on the Switch page.
 * Label the setting the switch controls, such as Payment emails.
 * @module
 */
import { Field, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.setting()}>
      <Field.Label>Payment emails</Field.Label>
      <Switch defaultChecked />
      <Field.Description>Email me when a payment settles.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const setting = style({ maxWidth: '20rem !custom', width: '100% !custom' })
}
```

**Don't:** Label the switch with its state.

```tsx
/**
 * Don't example for "Name the Setting, Not the State" on the Switch page.
 * Don't label the switch with its state.
 * @module
 */
import { Field, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.setting()}>
      <Field.Label>Enabled</Field.Label>
      <Switch defaultChecked />
      <Field.Description>Email me when a payment settles.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const setting = style({ maxWidth: '20rem !custom', width: '100% !custom' })
}
```

### Put the Label Above the Switch

Place each switch in a `Field.Root` below its `Field.Label`, as a text field sits, with the description under it.

**Do:** Place each switch below its `Field.Label`, with the description under it.

```tsx
/**
 * Do example for "Apply the Change Immediately" on the Switch page.
 * Save each setting the moment its switch flips.
 * @module
 */
import { Field, Fieldset, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Fieldset.Root {...styles.settings()}>
      <Field.Root>
        <Field.Label>Payment emails</Field.Label>
        <Switch defaultChecked />
        <Field.Description>Email me when a payment settles.</Field.Description>
      </Field.Root>
      <Field.Root>
        <Field.Label>Hide small balances</Field.Label>
        <Switch />
        <Field.Description>Hide tokens worth under $1.</Field.Description>
      </Field.Root>
    </Fieldset.Root>
  )
}

namespace styles {
  export const settings = style({ maxWidth: '20rem !custom', rowGap: '0', width: '100% !custom' })
}
```

**Don't:** Put the switch before its label, as a checkbox sits.

```tsx
/**
 * Don't example for "Put the Label Above the Switch" on the Switch page.
 * Don't put the switch before its label, as a checkbox sits.
 * @module
 */
import { Field, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Field.Root>
        <Field.Item>
          <Switch defaultChecked />
          <Field.Label>Payment emails</Field.Label>
        </Field.Item>
      </Field.Root>
      <Field.Root>
        <Field.Item>
          <Switch />
          <Field.Label>Hide small balances</Field.Label>
        </Field.Item>
      </Field.Root>
    </div>
  )
}

namespace styles {
  export const column = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '12',
    maxWidth: '20rem !custom',
    width: '100% !custom',
  })
}
```

### Explain Unavailable Settings

**Do:** Set `disabled` and state why in `Field.Description`.

```tsx
/**
 * Do example for "Explain Unavailable Settings" on the Switch page.
 * Set `disabled` and state why in `Field.Description`.
 * @module
 */
import { Field, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.setting()}>
      <Field.Label>Payment emails</Field.Label>
      <Switch disabled />
      <Field.Description>Verify your email to turn this on.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const setting = style({ maxWidth: '20rem !custom', width: '100% !custom' })
}
```

**Don't:** Dim a switch without a reason. It looks broken.

```tsx
/**
 * Don't example for "Explain Unavailable Settings" on the Switch page.
 * Don't dim a switch without a reason. It looks broken.
 * @module
 */
import { Field, style, Switch } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.setting()}>
      <Field.Label>Payment emails</Field.Label>
      <Switch disabled />
      <Field.Description>Email me when a payment settles.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const setting = style({ maxWidth: '20rem !custom', width: '100% !custom' })
}
```

## Content

* Describe what happens when the switch is on, such as Email me when a payment settles.
* Don't phrase labels as questions. Don't use negative labels, such as Don't show testnet tokens, which make on mean off.

## Accessibility

A switch follows the [WAI-ARIA switch pattern](https://www.w3.org/WAI/ARIA/apg/patterns/switch/).

### Semantics

* **Control (switch):** Announced with its on or off state.
* **Native TextInput (checkbox):** A hidden native input submits the value under `name`. It is outside the Tab order and the accessibility tree.
* **Label and Description (aria-labelledby):** In a field, the label names the switch and the field description describes it.
* **Disabled (aria-disabled):** Removes the switch from the Tab order.
* **Target Size (8px hit area):** The hit area reaches past the track on every side.
* **Reduced Motion (prefers-reduced-motion):** The thumb jumps instead of sliding, and only colors transition.

### Keyboard

* **Move Focus to the Switch (Tab):** Moves focus to the switch.
* **Toggle the Switch (Space or Enter):** Toggles the switch. A click toggles it too.

### Your Responsibilities

* **Keep the Thumb Visible:** The thumb position and the track color both show the state. Keep custom styles from hiding the thumb.

## Related

[Checkbox](/docs/components/checkbox)

Use for choices submitted with a form.

[Field](/docs/components/field)

Use for the label and description.

[Fieldset](/docs/components/fieldset)

Use for grouping settings rows.

[Toast](/docs/components/toast)

Use for reporting a failed save.
