Components / InputsStable

Checkbox

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

View as Markdown

Playground

At most one email a day, sent at 9:00.

Code

Checkbox.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
'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

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

Choose something else when

  • The change applies at once, with no Save: use Switch.
  • Only one option of several may be chosen: use Radio.

In the Nacre workspace

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

  • DoWrite the label as the thing that becomes true: Email me a weekly summary.

    Don'tWrite a negative such as Do not email me, which makes checked mean no.

  • DoGroup related checkboxes under a short heading.

    Don'tUse one checkbox to choose between two opposite options.

Anatomy

At most one email a day, sent at 9:00.
  1. Label. Body 14/20 in fg-strong, 12 px from the box. Clicking it toggles.
  2. Box. Radius 6 px, 1 px line border (line-strong on hover), surface fill; action fill when checked.
  3. Check. A 2 px on-action stroke, drawn in left to right with clip-path; a dash takes its place when indeterminate.
  4. Description. Caption 12/16 in fg-muted.

API

labelType stringDefault -Always required, a label element tied to the input.
descriptionType stringDefault -One line under the label, linked with aria-describedby.
checkedType booleanDefault -Controlled state (native attribute). Leave out to let the box keep its own.
defaultCheckedType booleanDefault falseStarting state when uncontrolled (native attribute).
indeterminateType booleanDefault falseShows a dash and is announced as mixed. Set it from the state of the items it controls.
invalidType booleanDefault falseError border and aria-invalid without a message, for a box in a group that shows one message for all.
errorType stringDefault -The message under the label; implies invalid and is linked with aria-describedby.
sizeType 'sm' | 'md'Default 'md'Box 16 or 20 px.
onCheckedChangeType (checked: boolean) => voidDefault -Called with the new state; onChange still works too.
refType Ref<HTMLInputElement>Default -Reaches the input element. React 19 passes ref as a plain prop, so no forwardRef wrapper is needed.
...restType InputHTMLAttributesDefault -Any native input attribute except type and size: name, value, required, disabled.

Motion

Check and uncheckProperty background-color, border-colorDuration quick 160Easing outKeyboard Same, colour only.
Check mark drawsProperty clip-path left to right, 40 ms after the fillDuration base 240Easing outKeyboard Space shows it at once.
Check mark growsProperty scale from .5, with opacityDuration base 240Easing springKeyboard At once.
Check mark leavesProperty opacity, scale to .5, blur 2 pxDuration instant 100Easing outKeyboard At once.
Indeterminate dashProperty clip-path from the centre out; crosses over with the checkDuration base 240Easing outKeyboard At once.
PressProperty scale to .9 (instant 100 out)Duration instant 100Easing outKeyboard Space does not squeeze.
ReleaseProperty scale back to 1, a small overshootDuration gentle 360Easing springKeyboard None.

Accessibility

Keyboard

Tab
Moves focus to the checkbox.
Space
Checks or unchecks it.

ARIA and semantics

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

Contrast

Check on the fillon-action on actionLight 17.74:1Dark 17.30:1Needs 3:1
Checked box on the pageaction on pageLight 16.14:1Dark 17.44: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