# Switch

Turns a setting on or off, and the change applies at once with no Save button.

Status: Stable. Group: Inputs.

## When to use

- Settings that take effect immediately: Focus mode, Show weekends, Dark calendar.
- Turning a feature on for a project, where the reader sees the result right away.

## When not to use

- The choice is saved later with the rest of a form. Use Checkbox instead.
- It starts an action rather than holding a state. Use Button instead.

## Scenarios

### Focus mode

The top bar has a Focus mode switch. Turning it on mutes notifications at once; the switch is the only place that says so.

### Calendar settings

Show weekends and Start the week on Monday are switches in a list. Each row has a short description of what changes.

## Do and avoid

- Do: Label the setting, not the action: Focus mode.
- Avoid: Write Turn on focus mode, which reads wrong once it is on.
- Do: Apply the change the moment the switch moves.
- Avoid: Ask for a Save after a switch; use a checkbox in that form instead.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | The setting, always in a real label element (hideLabel keeps it for assistive tech only). |
| `hideLabel` | `boolean` | `false` | Hides the label visually when the row already names the setting. |
| `description` | `string` |  | One line on what changes, linked with aria-describedby. |
| `invalid` | `boolean` | `false` | aria-invalid on the switch. The track keeps its on and off colours, since a switch applies at once. |
| `error` | `string` |  | The message under the label, for a change that failed to apply; implies invalid. |
| `checked` | `boolean` |  | Controlled state. Leave it out to let the switch keep its own state. |
| `defaultChecked` | `boolean` | `false` | Starting state when uncontrolled. |
| `onCheckedChange` | `(checked: boolean) => void` |  | Called with the new state on every toggle. |
| `size` | `'sm' \| 'md'` | `'md'` | Track 28 by 16 or 36 by 20 px. |
| `disabled` | `boolean` | `false` | Not available right now; the label says why nearby. |
| `ref` | `Ref<HTMLButtonElement>` |  | Reaches the switch button. React 19 passes ref as a plain prop, so no forwardRef wrapper is needed. |
| `...rest` | `ButtonHTMLAttributes` |  | Any native button attribute except value and children. |

## Anatomy

1. Label (`data-part="label"`): Body 14/20, 12 px from the track. Clicking it toggles the switch.
2. Track (`data-part="track"`): Full pill, switch-off or switch-on. The track is the button and carries the focus ring.
3. Thumb (`data-part="thumb"`): A ring: surface circle with shadow 1, inset 2 px, and a centre dot in the track colour; stays 3:1 against both track colours.
4. Description (`data-part="description"`): Caption 12/16 in fg-muted.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Toggle | thumb translate, settling with a small overshoot | base | spring | Space and Enter move the thumb at once. |
| Track and dot colour | background-color | quick | out | Same, colour only. |
| Press | thumb scaleX 1.25 toward the travel side, back edge held by translate | quick | out | Space and Enter do not stretch it. |
| Release | translate across and scale back to round, one spring | base | spring | None. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the switch. |
| Space or Enter | Turns it on or off. |

- A button with role switch and aria-checked, so screen readers say on or off.
- The visible label is a label element pointing at the switch, so it names it and clicking it toggles.
- State is never shown by colour alone: the thumb position changes too.
- invalid or error sets aria-invalid; the error message is linked with aria-describedby.

## Code

### Switch.tsx

```tsx
'use client'
import { useId, useState, type ButtonHTMLAttributes, type Ref } from 'react'
import { Note } from './Note'

// Nacre Switch: a setting that applies at once. React plus Tailwind classes only; needs nacre-theme.css.
// The thumb is a ring: a surface disc with a small centre dot in the track colour. Motion: the thumb slides base 240 on
// the spring curve and settles with a small overshoot, the track and the dot change colour quick 160. A pointer press
// stretches the thumb 25 % toward the side it will travel to (scale plus a matching translate, so its back edge stays
// put); letting go carries it over and back to round in one spring, retargeted from wherever it is. A key press (Space,
// Enter) moves the thumb at once, because keyboard actions never animate movement. Reduced motion or
// [data-nacre-motion="off"]: no movement.
// invalid marks it (aria-invalid only; the track keeps its on and off colours); error is the message under the label.

export type SwitchSize = 'sm' | 'md'

export type SwitchProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value' | 'children'> & {
  label: string
  hideLabel?: boolean
  description?: string
  invalid?: boolean
  error?: string
  checked?: boolean
  defaultChecked?: boolean
  onCheckedChange?: (checked: boolean) => void
  size?: SwitchSize
  ref?: Ref<HTMLButtonElement>
}

// Thumb inset 2 px. sm: 28x16 track, 12 px thumb, on at 28 - 12 - 2 = 14 px. md: 36x20, 16 px thumb, on at 18 px.
// Pressed, the thumb is 1.25 wide from its centre, so it shifts by an eighth of its width (1.5 or 2 px) toward the
// travel side to keep its back edge where it was.
const track: Record<SwitchSize, string> = { sm: 'mt-0.5 h-4 w-7', md: 'h-5 w-9' }
const thumb: Record<SwitchSize, string> = {
  sm:
    'size-3 translate-x-0.5 data-[state=on]:translate-x-3.5 after:inset-1 ' +
    'motion-safe:group-[:active:not(:focus-visible)]/track:translate-x-[3.5px] motion-safe:group-[:active:not(:focus-visible)]/track:data-[state=on]:translate-x-[12.5px]',
  md:
    'size-4 translate-x-0.5 data-[state=on]:translate-x-4.5 after:inset-[5px] ' +
    'motion-safe:group-[:active:not(:focus-visible)]/track:translate-x-1 motion-safe:group-[:active:not(:focus-visible)]/track:data-[state=on]:translate-x-4',
}

export function Switch({
  label,
  hideLabel = false,
  description,
  invalid = false,
  error,
  checked,
  defaultChecked = false,
  onCheckedChange,
  size = 'md',
  disabled,
  id,
  className = '',
  onClick,
  ref,
  ...rest
}: SwitchProps) {
  const auto = useId()
  const switchId = id ?? auto
  const descId = `${switchId}-desc`
  const errorId = `${switchId}-error`
  const bad = invalid || Boolean(error)
  const describedBy = [rest['aria-describedby'], description ? descId : undefined, error ? errorId : undefined].filter(Boolean).join(' ') || undefined
  const [inner, setInner] = useState(defaultChecked)
  const on = checked ?? inner
  const state = on ? 'on' : 'off'
  return (
    <div
      data-part="root"
      className={`group/switch flex items-start gap-3 ${className}`}
      onKeyDown={(e) => e.currentTarget.setAttribute('data-kbd', '')}
      onPointerDown={(e) => e.currentTarget.removeAttribute('data-kbd')}
    >
      <button
        ref={ref}
        id={switchId}
        type="button"
        role="switch"
        aria-checked={on}
        disabled={disabled}
        data-state={state}
        data-part="track"
        onClick={(e) => {
          onClick?.(e)
          if (e.defaultPrevented) return
          if (checked === undefined) setInner(!on)
          onCheckedChange?.(!on)
        }}
        className={`group/track inline-flex shrink-0 cursor-pointer items-center rounded-full transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:opacity-50 ${track[size]} ${on ? 'bg-switch-on' : 'bg-switch-off'}`}
        {...rest}
        aria-invalid={bad || undefined}
        aria-describedby={describedBy}
      >
        <span
          data-part="thumb"
          data-state={state}
          data-press-scale=""
          className={`relative rounded-full bg-surface shadow-1 after:absolute after:rounded-full after:transition-colors after:duration-(--nx-dur-quick) after:ease-out ${on ? 'after:bg-switch-on' : 'after:bg-switch-off'} transition-[translate,scale] duration-(--nx-dur-base) ease-spring motion-safe:group-[:active:not(:focus-visible)]/track:scale-x-125 group-active/track:duration-(--nx-dur-quick) group-active/track:ease-out group-disabled/track:after:bg-transparent group-data-[kbd]/switch:transition-none! ${thumb[size]}`}
        />
      </button>
      <span className="flex min-w-0 flex-col gap-0.5">
        <label data-part="label" htmlFor={switchId} className={hideLabel ? 'sr-only' : `text-body ${disabled ? 'cursor-not-allowed text-fg-disabled' : 'cursor-pointer text-fg-strong'}`}>
          {label}
        </label>
        {description && <span data-part="description" id={descId} className="text-caption text-fg-muted">{description}</span>}
        <Note as="span" part="error" id={errorId} className="[--nx-note-gap:2px]">{error}</Note>
      </span>
    </div>
  )
}
```

### Note.tsx

```tsx
'use client'
import { useEffect, useRef, useState, type ReactNode } from 'react'

// Nacre Note: the hint, error or success line under a field. It rolls out: the row grows from 0 to its height (base 240
// out) while the words fade and rise 4 px into place, so the fields below glide down instead of jumping. On the way out
// it keeps its last words on screen while the row rolls back up (quick 160), then unmounts the words. reserve keeps one
// line of space even when there is nothing to say, for a field whose message is likely to appear (no layout shift at all).
// With motion off or reduced, it changes at once. Parts: data-part="hint" (muted), "error" and "success" (their tone).
// React plus Tailwind classes only; needs nacre-theme.css. --nx-note-gap (default 6 px) is the gap the parent puts above
// the note, so the collapsed row cancels it.
export type NoteProps = {
  id?: string
  part: 'hint' | 'error' | 'success'
  children?: ReactNode
  className?: string
  as?: 'p' | 'span'
  /** Keep one line of space while empty. */
  reserve?: boolean
}

const tone = { hint: 'text-fg-muted', error: 'text-error-strong', success: 'text-success-strong' } as const

export function Note({ id, part, children, className = '', as: Tag = 'p', reserve = false }: NoteProps) {
  const has = children !== undefined && children !== null && children !== false && children !== ''
  const [last, setLast] = useState<ReactNode>(children)
  const el = useRef<HTMLElement>(null)
  const [leaving, setLeaving] = useState(false)
  const [seen, setSeen] = useState(has)
  if (has !== seen) {
    setSeen(has)
    setLeaving(!has)
  }
  if (has && children !== last) setLast(children)
  useEffect(() => {
    if (!leaving) return
    const node = el.current
    const raw = node ? getComputedStyle(node).transitionDuration.split(',')[0] : '0s'
    const ms = parseFloat(raw) * (raw.endsWith('ms') ? 1 : 1000)
    if (!ms) {
      setLeaving(false)
      return
    }
    const t = setTimeout(() => setLeaving(false), ms)
    return () => clearTimeout(t)
  }, [leaving])
  const Element = 'span' as unknown as 'p'
  const open = has
  const hasWords = has || leaving
  // The row: a one-cell grid whose track animates 0fr to 1fr. The negative margin cancels the parent's gap while closed.
  const wrap = open || reserve ? 'grid-rows-[1fr]' : 'grid-rows-[0fr] mt-[calc(var(--nx-note-gap,6px)*-1)]'
  const Wrap = Tag as 'p'
  return (
    <Wrap
      data-part="note"
      aria-hidden={hasWords ? undefined : true}
      className={`grid transition-[grid-template-rows,margin-top] ease-out ${open ? 'duration-(--nx-dur-base)' : 'duration-(--nx-dur-quick)'} ${wrap} ${className}`}
    >
      <span className="block min-h-0 overflow-hidden">
        {hasWords && (
          <Element
            ref={el as React.Ref<HTMLParagraphElement>}
            data-part={part}
            id={id}
            aria-hidden={has ? undefined : true}
            className={`block text-caption ${tone[part]} transition-[opacity,translate] duration-(--nx-dur-quick) ease-out starting:-translate-y-1 starting:opacity-0 ${has ? '' : '-translate-y-1 opacity-0'}`}
          >
            {has ? children : last}
          </Element>
        )}
        {reserve && !hasWords && <span className="block text-caption" aria-hidden="true">&nbsp;</span>}
      </span>
    </Wrap>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<div data-part="root" class="group/switch flex items-start gap-3 ">
  <button id="_R_0_" type="button" role="switch" aria-checked="false" data-state="off" data-part="track" class="group/track inline-flex shrink-0 cursor-pointer items-center rounded-full transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:opacity-50 h-5 w-9 bg-switch-off" aria-describedby="_R_0_-desc">
    <span data-part="thumb" data-state="off" data-press-scale="" class="relative rounded-full bg-surface shadow-1 after:absolute after:rounded-full after:transition-colors after:duration-(--nx-dur-quick) after:ease-out after:bg-switch-off transition-[translate,scale] duration-(--nx-dur-base) ease-spring motion-safe:group-[:active:not(:focus-visible)]/track:scale-x-125 group-active/track:duration-(--nx-dur-quick) group-active/track:ease-out group-disabled/track:after:bg-transparent group-data-[kbd]/switch:transition-none! size-4 translate-x-0.5 data-[state=on]:translate-x-4.5 after:inset-[5px] motion-safe:group-[:active:not(:focus-visible)]/track:translate-x-1 motion-safe:group-[:active:not(:focus-visible)]/track:data-[state=on]:translate-x-4"></span>
  </button>
  <span class="flex min-w-0 flex-col gap-0.5">
    <label data-part="label" for="_R_0_" class="text-body cursor-pointer text-fg-strong">Focus mode</label>
    <span data-part="description" id="_R_0_-desc" class="text-caption text-fg-muted">Mute notifications until you turn it off.</span>
    <span data-part="note" aria-hidden="true" class="grid transition-[grid-template-rows,margin-top] ease-out duration-(--nx-dur-quick) grid-rows-[0fr] mt-[calc(var(--nx-note-gap,6px)*-1)] [--nx-note-gap:2px]">
      <span class="block min-h-0 overflow-hidden"></span>
    </span>
  </span>
</div>
```

## Related

- [Button](https://enxm.me/services/design-systems/nacre/components/button)
- [Checkbox](https://enxm.me/services/design-systems/nacre/components/checkbox)
