Components / InputsStable

Radio

Picks exactly one option from a short list that stays visible, so people can compare before choosing.

View as Markdown

Playground

Who can see this project
Five people today.

Code

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

// Nacre Radio: pick exactly one of a short visible list. A fieldset of native radios drawn by CSS, so arrow keys work
// the platform way. React plus Tailwind classes only; needs nacre-theme.css. Motion: the new dot grows from .6 with
// opacity on the spring curve (base 240, a small overshoot) while the old one shrinks back to .6 and fades, quicker
// (instant 100), so a fast run of clicks retargets instead of restarting. A pointer press squeezes the circle to .9 and
// lets go on the spring. With the keyboard (arrow keys) the choice swaps at once; reduced motion or
// [data-nacre-motion="off"]: no movement.
// invalid marks the group; error is the message (it replaces the hint and implies invalid). ref reaches the fieldset.

export type RadioOption = { value: string; label: string; description?: string; disabled?: boolean }

export type RadioGroupProps = {
  label: string
  options: RadioOption[]
  name?: string
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  orientation?: 'vertical' | 'horizontal'
  size?: 'sm' | 'md'
  disabled?: boolean
  required?: boolean
  invalid?: boolean
  hint?: string
  error?: string
  className?: string
  ref?: Ref<HTMLFieldSetElement>
}

// The circle squeezes on a pointer press (arrow keys and Space leave focus-visible, so they do not) and springs back.
const press =
  'transition-[scale] duration-(--nx-dur-gentle) ease-spring ' +
  'motion-safe:group-[:active:not(:has(:focus-visible,:disabled))]/item:scale-90 group-active/item:duration-(--nx-dur-instant) group-active/item:ease-out'

// Leaving: quick fade and shrink. Arriving: opacity instant, scale on the spring. Keyboard: no transition at all.
const dot =
  '[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-instant)_var(--nx-ease-out)] ' +
  'peer-checked:[transition:opacity_var(--nx-dur-instant)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring)] group-data-[kbd]/radio:transition-none!'

export function RadioGroup({
  label,
  options,
  name,
  value,
  defaultValue,
  onValueChange,
  orientation = 'vertical',
  size = 'md',
  disabled = false,
  required,
  invalid = false,
  hint,
  error,
  className = '',
  ref,
}: RadioGroupProps) {
  const auto = useId()
  const groupName = name ?? auto
  const hintId = `${auto}-hint`
  const bad = invalid || Boolean(error)
  const note = error || hint
  const [inner, setInner] = useState(defaultValue)
  const current = value ?? inner
  const choose = (v: string) => {
    if (value === undefined) setInner(v)
    onValueChange?.(v)
  }
  const border = bad ? 'border-error' : 'border-line enabled:hover:border-line-strong'
  return (
    <fieldset
      data-part="root"
      ref={ref}
      disabled={disabled}
      aria-describedby={note ? hintId : undefined}
      onKeyDown={(e) => e.currentTarget.setAttribute('data-kbd', '')}
      onPointerDown={(e) => e.currentTarget.removeAttribute('data-kbd')}
      className={`group/radio m-0 flex min-w-0 flex-col gap-3 border-0 p-0 ${className}`}
    >
      <legend data-part="legend" className="mb-3 p-0 text-label text-fg-strong">{label}</legend>
      <div className={orientation === 'horizontal' ? 'flex flex-wrap gap-x-6 gap-y-3' : 'flex flex-col gap-3'}>
        {options.map((o, n) => {
          const id = `${auto}-${n}`
          const off = disabled || o.disabled
          return (
            <div key={o.value} data-part="item" className="group/item flex items-start gap-3">
              <span data-press-scale="" className={`${press} relative inline-grid shrink-0 place-items-center ${size === 'sm' ? 'mt-[3px] size-3.5' : 'mt-px size-[18px]'}`}>
                <input
                  id={id}
                  type="radio"
                  name={groupName}
                  value={o.value}
                  checked={current === o.value}
                  disabled={o.disabled}
                  required={required}
                  {...(bad ? { 'aria-invalid': true } : {})}
                  aria-describedby={o.description ? `${id}-desc` : undefined}
                  onChange={() => choose(o.value)}
                  data-part="control"
                  className={`peer col-start-1 row-start-1 m-0 size-full cursor-pointer appearance-none rounded-full border bg-surface transition-[border-color] duration-(--nx-dur-quick) ease-out checked:border-accent/45 focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--nx-fg-muted)_16%,transparent)] disabled:cursor-not-allowed disabled:border-line-subtle disabled:bg-sunken ${border}`}
                />
                <span
                  data-part="dot"
                  aria-hidden="true"
                  className={`pointer-events-none absolute inset-0 m-auto ${size === 'sm' ? 'size-1.5' : 'size-2'} scale-[.6] rounded-full bg-accent opacity-0 peer-checked:scale-100 peer-checked:opacity-100 peer-disabled:bg-fg-disabled ${dot}`}
                />
              </span>
              <span className="flex min-w-0 flex-col gap-0.5">
                <label data-part="label" htmlFor={id} className={`text-body ${off ? 'cursor-not-allowed text-fg-disabled' : 'cursor-pointer text-fg-strong'}`}>{o.label}</label>
                {o.description && <span id={`${id}-desc`} className="text-caption text-fg-muted">{o.description}</span>}
              </span>
            </div>
          )
        })}
      </div>
      <Note part={error ? 'error' : 'hint'} id={hintId} className="[--nx-note-gap:12px]">{error || hint}</Note>
    </fieldset>
  )
}
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

  • Two to five options where the differences matter: who can see a project.
  • A setting with a clear default that people should see next to its alternatives.

Choose something else when

In the Nacre workspace

Project visibility

Everyone in the workspace, Only the project team, Only me. The team option has a description with the head count.

Reminder timing

In a calendar event, a horizontal group offers 10 minutes, 1 hour and 1 day before.

Do and don't

  • DoPreselect the safest sensible option.

    Don'tLeave a required group empty with no hint of what is expected.

  • DoKeep labels parallel and short, in a meaningful order.

    Don'tMix sentence lengths and orders so the options are hard to compare.

Anatomy

Who can see this project
Five people today.
  1. Legend. The question, label 13/16 at weight 500, 12 px above the first option.
  2. Ring and dot. Full circle, 1 px line border on surface. The chosen option gets a soft accent border and an accent dot half the size of the ring.
  3. Option label. Body 14/20, 12 px from the ring. Clicking it chooses the option.

API

labelType stringDefault -The question, rendered as the legend of the fieldset.
optionsType RadioOption[]Default -value, label, optional description and disabled for each option.
nameType stringDefault generatedThe form field name shared by the radios.
valueType stringDefault -Controlled value.
defaultValueType stringDefault -Starting value when uncontrolled.
onValueChangeType (value: string) => voidDefault -Called with the chosen value.
orientationType 'vertical' | 'horizontal'Default 'vertical'Horizontal wraps on narrow screens.
sizeType 'sm' | 'md'Default 'md'Ring 16 or 20 px.
disabledType booleanDefault falseDisables the whole group through the fieldset.
requiredType booleanDefault -Native required on every radio.
invalidType booleanDefault falseError borders and aria-invalid on every radio, without changing the hint.
hintType stringDefault -Text under the group, linked to the fieldset with aria-describedby.
errorType stringDefault -The message: replaces the hint in the same place, implies invalid, linked to the fieldset with aria-describedby.
refType Ref<HTMLFieldSetElement>Default -Reaches the fieldset, so a form can focus the group (focus its first radio). React 19 passes ref as a plain prop.

Motion

Dot arrivesProperty scale from .6 with a small overshoot, opacityDuration base 240Easing springKeyboard Arrow keys swap the dot at once.
Dot leavesProperty scale back to .6, opacityDuration instant 100Easing outKeyboard At once.
PressProperty circle scale to .9Duration instant 100Easing outKeyboard Arrow keys and Space do not squeeze.
ReleaseProperty scale back to 1Duration gentle 360Easing springKeyboard None.
RingProperty border-colorDuration quick 160Easing outKeyboard Same, colour only.
Who can see this project
Five people today.

Accessibility

Keyboard

Tab
Moves focus to the chosen option, or the first one when none is chosen.
Arrow keys
Move to the next or previous option and choose it.
Space
Chooses the focused option when none is chosen yet.

ARIA and semantics

  • A fieldset with a legend, so the question is read before each option.
  • Native radios sharing one name: the browser provides the arrow-key model and the position in the set.
  • Option descriptions are linked with aria-describedby; the hint is linked to the whole group.
  • invalid or error sets aria-invalid on each radio; the error message is linked with aria-describedby on the fieldset.

Contrast

Dot and chosen ringaction on surfaceLight 17.74:1Dark 16.29:1Needs 3:1
Legend and labelsfg-strong on pageLight 17.30:1Dark 17.44:1Needs 4.5:1
Error hinterror-strong on pageLight 5.46:1Dark 11.77:1Needs 4.5:1