# Switch

> An on/off switch from @salmonui/inputs/switch on a native checkbox with role="switch", a label, description and form submission.

Canonical: https://salmonui.dev/docs/inputs/switch

`Switch` is an on/off toggle. It is a native
`<input type="checkbox" role="switch">` drawn as a track and a thumb,
labelled by its children through a real `<label for>`.

```tsx
import { Switch } from '@salmonui/inputs/switch';
import '@salmonui/inputs/switch/styles.css';

<Switch name="wifi" defaultChecked description="Uses mobile data when off">Wi-Fi</Switch>
```

### Live demo: Switch basics

Live demo: https://salmonui.dev/demos/inputs/switch-basics

Switches with a description, a start label, a thumb icon and a controlled switch that vetoes a change.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Switch } from '@salmonui/inputs/switch';

// Uncontrolled and controlled switches; the controlled one vetoes turning on without Wi-Fi.
export default function SwitchBasicsDemo() {
  const [wifi, setWifi] = useState(true);
  const [sync, setSync] = useState(false);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <Switch checked={wifi} onCheckedChange={(on) => (setWifi(on), on || setSync(false))} description={wifi ? 'Connected' : 'Off'}>
        Wi-Fi
      </Switch>
      <Switch labelPlacement="start" defaultChecked thumbIcon="✓">
        Bluetooth
      </Switch>
      <Switch checked={sync} onCheckedChange={(on) => (wifi || !on) && setSync(on)}>
        Sync over Wi-Fi only
      </Switch>
    </div>
  );
}
```

## Checked state

`checked` / `defaultChecked` / `onCheckedChange(checked, details)` with `details.source` (`'pointer'`, `'touch'`, `'keyboard'`,
`'api'`) and `details.reason` (`'toggle'` or `'reset'`). A controlled
`checked` is also the veto: ignore the proposal and the switch
stays as it is.

```tsx
const [on, setOn] = useState(false);
<Switch checked={on} onCheckedChange={(next) => (canEnable || !next) && setOn(next)}>Sync</Switch>
```

Without `checked` the switch is uncontrolled and a form reset restores
`defaultChecked`.

### Live demo: Choice events

Live demo: https://salmonui.dev/demos/inputs/choice-events

Change events of RadioGroup, Radio, Checkbox and Switch with their details, radio labels before or after the control, and standalone radios grouped by a shared native name.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Switch } from '@salmonui/inputs/switch';
import { EventLog, useEventLog } from '../../components/demo-kit';

// Change events of the choice controls, radio labels before the control and
// standalone radios grouped only by a shared native `name`.
export default function ChoiceEventsDemo() {
  const [log, push] = useEventLog(12);
  const [shipping, setShipping] = useState<string | null>('standard');
  const [standalone, setStandalone] = useState('monthly');
  return (
    <>
      <div style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}>
        <RadioGroup
          label="Shipping"
          name="ce-shipping"
          labelPlacement="start"
          value={shipping}
          onValueChange={(value, details) => {
            setShipping(value);
            push(`RadioGroup onValueChange ${JSON.stringify(value)} (${details.reason}, ${details.source})`);
          }}
        >
          <Radio value="standard">Standard, 3 to 5 days</Radio>
          <Radio value="express">Express, next day</Radio>
          <Radio value="pickup" labelPlacement="end">
            Pick up in store (label after)
          </Radio>
        </RadioGroup>
        <div role="group" aria-labelledby="ce-billing-label" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '4px 16px' }}>
          <span id="ce-billing-label" style={{ flexBasis: '100%', fontWeight: 'var(--salmon-font-weight-medium)' }}>
            Billing (standalone radios)
          </span>
          <Radio name="ce-billing" value="monthly" checked={standalone === 'monthly'} onChange={(event) => (setStandalone(event.target.value), push(`Radio onChange ${event.target.value}`))}>
            Monthly
          </Radio>
          <Radio name="ce-billing" value="yearly" checked={standalone === 'yearly'} onChange={(event) => (setStandalone(event.target.value), push(`Radio onChange ${event.target.value}`))}>
            Yearly
          </Radio>
        </div>
        <Checkbox name="ce-terms" value="accepted" onCheckedChange={(checked, details) => push(`Checkbox onCheckedChange ${checked} (${details.source})`)}>
          I accept the terms
        </Checkbox>
        <Switch name="ce-dark" value="on" onCheckedChange={(checked, details) => push(`Switch onCheckedChange ${checked} (${details.source})`)}>
          Dark receipts
        </Switch>
      </div>
      <p className="demo-status">
        Shipping {JSON.stringify(shipping)} · Billing {JSON.stringify(standalone)}
      </p>
      <EventLog entries={log} label="Change events" />
    </>
  );
}
```

## Label

Children are the label and `labelPlacement: 'start' | 'end'` places it.
`thumbIcon` draws a decorative icon inside the thumb.

## Form submission

`name`, `value` (default `'on'`), `form` and `required` are native: an on switch submits `name=value`.

## Keyboard

| Key | Action |
| --- | --- |
| Space | Toggles the switch |
| Tab / Shift+Tab | Moves focus |

Screen readers hear "switch, on" or "off" from the native checked state and
`role="switch"`. The thumb moves with logical properties, so it
mirrors in right-to-left content. Try it in the
[keyboard demo](https://salmonui.dev/demos/inputs/inputs-keyboard), and see the
[form demo](https://salmonui.dev/demos/inputs/field-forms) for submission.

## SSR

The switch is a native checkbox, so the server markup is final: ids come
from `useId` and the checked state is right before hydration.

## Design notes

- there is no text inside the track: text in a fixed-width track breaks with translated strings, and `role="switch"`
  already announces the state. Use the label, a `description` that
  reflects `checked`, or `thumbIcon`.
- no toggle method: the `ref` is the native input and toggling
  is a state change of the owner. Use `setChecked((c) => !c)` on a
  controlled switch.
- no before-change event: with a controlled `checked` the owner already
  decides every change. Move the condition into `onCheckedChange` and only
  call `setChecked` when it passes.

## API

| Prop | Type | Default |
| --- | --- | --- |
| `checked`, `defaultChecked` | `boolean` | `false` |
| `onCheckedChange` | `(checked, { source, reason }) => void` | |
| `children` | `ReactNode` (label) | |
| `labelPlacement` | `'start' \| 'end'` | `'end'` |
| `thumbIcon` | `ReactNode` | |
| `name`, `value`, `form`, `required`, `disabled` | native | `value: 'on'` |
| `description`, `errorMessage`, `invalid`, `validation`, `validateOn` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` |
| `classNames` | `{ input, label, description, error }` | |
| `ref` | `HTMLInputElement` | |

Full signatures: [`@salmonui/inputs/switch` API reference](https://salmonui.dev/docs/reference/inputs/switch).
