# Checkbox

Turns one option on or off inside a form that is saved later; several can be on at once.

Status: Stable. Group: Inputs.

## When to use

- A list of independent preferences, such as which notifications to receive.
- Selecting rows in a table, with an indeterminate header box when only some are selected.
- A single agreement before a step, such as accepting the workspace terms.

## When not to use

- The change applies at once, with no Save. Use Switch instead.
- Only one option of several may be chosen. Use Radio instead.

## Scenarios

### Notification settings

Email me when a task is assigned, Email me a weekly summary: each a Checkbox with one line of description, saved with the form.

### Bulk select tasks

The header Checkbox of the task table turns indeterminate when some rows are selected, and selects all on click.

## Do and avoid

- Do: Write the label as the thing that becomes true: Email me a weekly summary.
- Avoid: Write a negative such as Do not email me, which makes checked mean no.
- Do: Group related checkboxes under a short heading.
- Avoid: Use one checkbox to choose between two opposite options.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | Always required, a label element tied to the input. |
| `description` | `string` |  | One line under the label, linked with aria-describedby. |
| `checked` | `boolean` |  | Controlled state (native attribute). Leave out to let the box keep its own. |
| `defaultChecked` | `boolean` | `false` | Starting state when uncontrolled (native attribute). |
| `indeterminate` | `boolean` | `false` | Shows a dash and is announced as mixed. Set it from the state of the items it controls. |
| `invalid` | `boolean` | `false` | Error border and aria-invalid without a message, for a box in a group that shows one message for all. |
| `error` | `string` |  | The message under the label; implies invalid and is linked with aria-describedby. |
| `size` | `'sm' \| 'md'` | `'md'` | Box 16 or 20 px. |
| `onCheckedChange` | `(checked: boolean) => void` |  | Called with the new state; onChange still works too. |
| `ref` | `Ref<HTMLInputElement>` |  | Reaches the input element. React 19 passes ref as a plain prop, so no forwardRef wrapper is needed. |
| `...rest` | `InputHTMLAttributes` |  | Any native input attribute except type and size: name, value, required, disabled. |

## Anatomy

1. Label (`data-part="label"`): Body 14/20 in fg-strong, 12 px from the box. Clicking it toggles.
2. Box (`data-part="box"`): Radius 6 px, 1 px line border (line-strong on hover), surface fill; action fill when checked.
3. Check (`data-part="check"`): A 2 px on-action stroke, drawn in left to right with clip-path; a dash takes its place when indeterminate.
4. Description (`data-part="description"`): Caption 12/16 in fg-muted.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Check and uncheck | background-color, border-color | quick | out | Same, colour only. |
| Check mark draws | clip-path left to right, 40 ms after the fill | base | out | Space shows it at once. |
| Check mark grows | scale from .5, with opacity | base | spring | At once. |
| Check mark leaves | opacity, scale to .5, blur 2 px | instant | out | At once. |
| Indeterminate dash | clip-path from the centre out; crosses over with the check | base | out | At once. |
| Press | scale to .9 (instant 100 out) | instant | out | Space does not squeeze. |
| Release | scale back to 1, a small overshoot | gentle | spring | None. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the checkbox. |
| Space | Checks or unchecks it. |

- A native input type checkbox, so state and name are announced without extra roles.
- indeterminate is set as a DOM property and announced as mixed.
- The description is linked with aria-describedby. invalid or error sets aria-invalid; the error message is linked with aria-describedby.

## Code

### Checkbox.tsx

```tsx
'use client'
import { useEffect, useId, useRef, type InputHTMLAttributes, type Ref } from 'react'
import { Note } from './Note'

// Nacre Checkbox: one option in a form that is saved later. A native checkbox drawn by CSS; React plus Tailwind classes
// only, needs nacre-theme.css. Motion: the fill changes quick 160 out; the check draws in left to right (clip-path,
// base 240 out, 40 ms after the fill) while it grows from .5 on the spring curve; unchecking blurs it out faster
// (instant 100), so a quick double click retargets instead of restarting. Indeterminate draws a dash out from its
// centre, and check and dash cross over. A pointer press squeezes the box to .9 and lets go on the spring. Space changes
// it at once (keyboard actions never animate). Reduced motion or [data-nacre-motion="off"]: every change is instant.
// invalid marks the box without a message (a group owns it); error is the message under the label and implies invalid.

// checked and defaultChecked are native input attributes and reach the input through ...rest.
export type CheckboxSize = 'sm' | 'md'

export type CheckboxProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'type'> & {
  label: string
  description?: string
  indeterminate?: boolean
  invalid?: boolean
  error?: string
  size?: CheckboxSize
  onCheckedChange?: (checked: boolean) => void
  ref?: Ref<HTMLInputElement>
}

// The box squeezes on a pointer press (not Space, which leaves focus-visible on the input) and springs back.
const press =
  'transition-[scale] duration-(--nx-dur-gentle) ease-spring ' +
  'motion-safe:group-[:active:not(:has(:focus-visible,:disabled))]/checkbox:scale-90 group-active/checkbox:duration-(--nx-dur-instant) group-active/checkbox:ease-out'

// Hidden marks wait small, blurred and clipped; leaving is quicker than arriving, and the clip resets only once the
// mark has faded, so it never draws backwards. Shown: the clip opens base 240 out (40 ms late) while it springs to 1.
const mark =
  'pointer-events-none col-start-1 row-start-1 size-3/4 text-on-action scale-50 opacity-0 blur-[2px] group-data-[kbd]/checkbox:transition-none! ' +
  '[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-instant)_var(--nx-ease-out),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_0s_linear_var(--nx-dur-instant)]'
const checkOn =
  '[clip-path:inset(0_100%_0_0)] peer-[:checked:not(:indeterminate)]:[clip-path:inset(0)] peer-[:checked:not(:indeterminate)]:scale-100 ' +
  'peer-[:checked:not(:indeterminate)]:opacity-100 peer-[:checked:not(:indeterminate)]:blur-[0px] ' +
  'peer-[:checked:not(:indeterminate)]:[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_var(--nx-dur-base)_var(--nx-ease-out)_40ms]'
const dashOn =
  '[clip-path:inset(0_50%)] peer-indeterminate:[clip-path:inset(0)] peer-indeterminate:scale-100 peer-indeterminate:opacity-100 peer-indeterminate:blur-[0px] ' +
  'peer-indeterminate:[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_var(--nx-dur-base)_var(--nx-ease-out)_40ms]'

export function Checkbox({ label, description, indeterminate = false, invalid = false, error, size = 'md', onCheckedChange, onChange, disabled, id, className = '', ref, ...rest }: CheckboxProps) {
  const auto = useId()
  const inputId = id ?? auto
  const descId = `${inputId}-desc`
  const errorId = `${inputId}-error`
  const bad = invalid || Boolean(error)
  const describedBy = [rest['aria-describedby'], description ? descId : undefined, error ? errorId : undefined].filter(Boolean).join(' ') || undefined
  const inner = useRef<HTMLInputElement | null>(null)
  // Indeterminate is a DOM property, not an attribute.
  useEffect(() => {
    if (inner.current) inner.current.indeterminate = indeterminate
  })
  const setRef = (el: HTMLInputElement | null) => {
    inner.current = el
    if (typeof ref === 'function') ref(el)
    else if (ref) ref.current = el
  }
  const border = bad ? 'border-error' : 'border-line enabled:hover:border-line-strong'
  return (
    <div
      data-part="root"
      className={`group/checkbox flex items-start gap-3 ${className}`}
      onKeyDown={(e) => e.currentTarget.setAttribute('data-kbd', '')}
      onPointerDown={(e) => e.currentTarget.removeAttribute('data-kbd')}
    >
      <span data-part="box" data-press-scale="" className={`${press} relative inline-grid shrink-0 place-items-center ${size === 'sm' ? 'mt-0.5 size-4' : 'size-5'}`}>
        <input
          ref={setRef}
          id={inputId}
          type="checkbox"
          disabled={disabled}
          onChange={(e) => {
            onChange?.(e)
            onCheckedChange?.(e.target.checked)
            // A click clears the DOM flag; a prop that is still true puts it back.
            if (indeterminate) e.target.indeterminate = true
          }}
          className={`peer col-start-1 row-start-1 m-0 size-full cursor-pointer appearance-none rounded-[6px] border bg-surface transition-[background-color,border-color] duration-(--nx-dur-quick) ease-out checked:border-action checked:bg-action indeterminate:border-action indeterminate:bg-action focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:border-line-subtle disabled:bg-sunken disabled:checked:border-line-strong disabled:checked:bg-line-strong disabled:indeterminate:border-line-strong disabled:indeterminate:bg-line-strong ${border}`}
          {...rest}
          aria-invalid={bad || undefined}
          aria-describedby={describedBy}
        />
        <svg data-part="check" aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={`${mark} ${checkOn}`}>
          <path d="M3.5 8.5l3 3 6-7" />
        </svg>
        <svg data-part="dash" aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" className={`${mark} ${dashOn}`}>
          <path d="M4 8h8" />
        </svg>
      </span>
      <span className="flex min-w-0 flex-col gap-0.5">
        <label data-part="label" htmlFor={inputId} className={`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/checkbox flex items-start gap-3 ">
  <span data-part="box" data-press-scale="" class="transition-[scale] duration-(--nx-dur-gentle) ease-spring motion-safe:group-[:active:not(:has(:focus-visible,:disabled))]/checkbox:scale-90 group-active/checkbox:duration-(--nx-dur-instant) group-active/checkbox:ease-out relative inline-grid shrink-0 place-items-center size-5">
    <input id="_R_0_" type="checkbox" class="peer col-start-1 row-start-1 m-0 size-full cursor-pointer appearance-none rounded-[6px] border bg-surface transition-[background-color,border-color] duration-(--nx-dur-quick) ease-out checked:border-action checked:bg-action indeterminate:border-action indeterminate:bg-action focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:border-line-subtle disabled:bg-sunken disabled:checked:border-line-strong disabled:checked:bg-line-strong disabled:indeterminate:border-line-strong disabled:indeterminate:bg-line-strong border-line enabled:hover:border-line-strong" aria-describedby="_R_0_-desc"/>
    <svg data-part="check" aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pointer-events-none col-start-1 row-start-1 size-3/4 text-on-action scale-50 opacity-0 blur-[2px] group-data-[kbd]/checkbox:transition-none! [transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-instant)_var(--nx-ease-out),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_0s_linear_var(--nx-dur-instant)] [clip-path:inset(0_100%_0_0)] peer-[:checked:not(:indeterminate)]:[clip-path:inset(0)] peer-[:checked:not(:indeterminate)]:scale-100 peer-[:checked:not(:indeterminate)]:opacity-100 peer-[:checked:not(:indeterminate)]:blur-[0px] peer-[:checked:not(:indeterminate)]:[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_var(--nx-dur-base)_var(--nx-ease-out)_40ms]">
      <path d="M3.5 8.5l3 3 6-7"></path>
    </svg>
    <svg data-part="dash" aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" class="pointer-events-none col-start-1 row-start-1 size-3/4 text-on-action scale-50 opacity-0 blur-[2px] group-data-[kbd]/checkbox:transition-none! [transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-instant)_var(--nx-ease-out),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_0s_linear_var(--nx-dur-instant)] [clip-path:inset(0_50%)] peer-indeterminate:[clip-path:inset(0)] peer-indeterminate:scale-100 peer-indeterminate:opacity-100 peer-indeterminate:blur-[0px] peer-indeterminate:[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),filter_var(--nx-dur-instant)_var(--nx-ease-out),clip-path_var(--nx-dur-base)_var(--nx-ease-out)_40ms]">
      <path d="M4 8h8"></path>
    </svg>
  </span>
  <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">Email me when a task is assigned to me</label>
    <span data-part="description" id="_R_0_-desc" class="text-caption text-fg-muted">At most one email a day, sent at 9:00.</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

- [Radio](https://enxm.me/services/design-systems/nacre/components/radio)
- [Switch](https://enxm.me/services/design-systems/nacre/components/switch)
