Components / InputsStable

Switch

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

View as Markdown

Playground

Mute notifications until you turn it off.

Code

Switch.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
'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>
  )
}

Usage

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.

Choose something else when

  • The choice is saved later with the rest of a form: use Checkbox.
  • It starts an action rather than holding a state: use Button.

In the Nacre workspace

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 don't

  • DoLabel the setting, not the action: Focus mode.

    Don'tWrite Turn on focus mode, which reads wrong once it is on.

  • DoApply the change the moment the switch moves.

    Don'tAsk for a Save after a switch; use a checkbox in that form instead.

Anatomy

Mute notifications until you turn it off.
  1. Label. Body 14/20, 12 px from the track. Clicking it toggles the switch.
  2. Track. Full pill, switch-off or switch-on. The track is the button and carries the focus ring.
  3. 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. Caption 12/16 in fg-muted.

API

labelType stringDefault -The setting, always in a real label element (hideLabel keeps it for assistive tech only).
hideLabelType booleanDefault falseHides the label visually when the row already names the setting.
descriptionType stringDefault -One line on what changes, linked with aria-describedby.
invalidType booleanDefault falsearia-invalid on the switch. The track keeps its on and off colours, since a switch applies at once.
errorType stringDefault -The message under the label, for a change that failed to apply; implies invalid.
checkedType booleanDefault -Controlled state. Leave it out to let the switch keep its own state.
defaultCheckedType booleanDefault falseStarting state when uncontrolled.
onCheckedChangeType (checked: boolean) => voidDefault -Called with the new state on every toggle.
sizeType 'sm' | 'md'Default 'md'Track 28 by 16 or 36 by 20 px.
disabledType booleanDefault falseNot available right now; the label says why nearby.
refType Ref<HTMLButtonElement>Default -Reaches the switch button. React 19 passes ref as a plain prop, so no forwardRef wrapper is needed.
...restType ButtonHTMLAttributesDefault -Any native button attribute except value and children.

Motion

ToggleProperty thumb translate, settling with a small overshootDuration base 240Easing springKeyboard Space and Enter move the thumb at once.
Track and dot colourProperty background-colorDuration quick 160Easing outKeyboard Same, colour only.
PressProperty thumb scaleX 1.25 toward the travel side, back edge held by translateDuration quick 160Easing outKeyboard Space and Enter do not stretch it.
ReleaseProperty translate across and scale back to round, one springDuration base 240Easing springKeyboard None.
Mute notifications until you turn it off.

Accessibility

Keyboard

Tab
Moves focus to the switch.
Space or Enter
Turns it on or off.

ARIA and semantics

  • 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.

Contrast

Off track on the pageswitch-off on pageLight 3.40:1Dark 3.98:1Needs 3:1
On track on the pageswitch-on on pageLight 4.88:1Dark 8.25:1Needs 3:1
Thumb on the off tracksurface on switch-offLight 3.74:1Dark 3.72:1Needs 3:1
Thumb on the on tracksurface on switch-onLight 5.37:1Dark 7.71:1Needs 3:1
Labelfg-strong on pageLight 17.30:1Dark 17.44:1Needs 4.5:1
Descriptionfg-muted on pageLight 5.07:1Dark 7.15:1Needs 4.5:1