# Radio group

One choice among a few, as glass radio rows whose white bead springs in, with arrow keys that skip what can't be picked and a risky option set in the warning color.

Tier: free. Type: component. Category: selection. Tags: settings, permissions, form, keyboard, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/radio-group.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/radio-group.tsx`.

## Preview

Live preview: https://pixilui.com/components/radio-group

Knobs:

- `save`: `instant`, `fails`

Signature: Pick an option and its white bead springs in with a little overshoot on the candy glass, while the old one simply clears.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/radio-group.tsx, quiet https://pixilui.com/r/standalone/radio-group.quiet.tsx.

## Code

`components/pixilui/radio-group.tsx`

```tsx
"use client";

/*
  The radio group, locked 27 Nov 2026 with the toggles (design/explorations/components/locked/toggles).
  Its look and motion are foundation.css section 8 (.pixilui-radio); this file writes the locked markup
  and plays the locked behavior (toggles.js):

  Radio     a 14px white glass cap; picked, the candy glass cross-fades in (200ms) and the white bead
            springs in (260ms, the pop curve). Hover previews a faint bead.
  Keys      arrow keys move the pick and skip disabled options; the pick wraps around; Tab leaves the
            group (one radio takes focus: roving tabindex).
  Pending   onValueChange may return a promise: the new pick shows at once, the group is aria-busy until
            it settles, and the pick goes back if it rejects.
  Reduced   no transitions, the bead shown at once.
*/

import {
  createContext,
  forwardRef,
  useCallback,
  useContext,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type ComponentPropsWithoutRef,
  type KeyboardEvent,
  type ReactNode,
} from "react";
import { cn } from "./lib/utils";

type Group = {
  value: string | null;
  /** The radio that takes focus when none is picked: the first one that can be. */
  first: string | null;
  pick: (value: string) => void;
  register: (el: HTMLButtonElement, value: string) => () => void;
  name?: string;
  disabled?: boolean;
};
const GroupContext = createContext<Group | null>(null);

export type RadioGroupProps = Omit<ComponentPropsWithoutRef<"div">, "onChange" | "defaultValue" | "role"> & {
  /** Controlled: the picked value. */
  value?: string | null;
  /** Uncontrolled: the value picked on the first render. */
  defaultValue?: string | null;
  /** Runs with the new pick. Return a promise to save first: the group is aria-busy until it settles, and the pick goes back if it rejects. */
  onValueChange?: (value: string) => void | Promise<void>;
  /** A form field name: a hidden input carries the picked value. */
  name?: string;
  /** Disables every option. */
  disabled?: boolean;
  /** The group's accessible name: the question the options answer. */
  "aria-label"?: string;
  /** RadioGroupItem rows. */
  children?: ReactNode;
};

/** One choice among a few: radio rows whose white bead springs in, with arrow keys between them. */
export const RadioGroup = forwardRef<HTMLDivElement, RadioGroupProps>(function RadioGroup(
  { value, defaultValue = null, onValueChange, name, disabled, className, children, onKeyDown, ...props },
  ref,
) {
  const [own, setOwn] = useState<string | null>(defaultValue);
  const [pending, setPending] = useState<string | null>(null);
  const [first, setFirst] = useState<string | null>(null);
  const current = pending ?? (value !== undefined ? value : own);
  const radios = useRef(new Map<HTMLButtonElement, string>());
  const root = useRef<HTMLDivElement | null>(null);

  /** The radios that can be picked, in the order they stand. */
  const enabled = () => [...(root.current?.querySelectorAll<HTMLButtonElement>(".pixilui-radio[role=radio]:not(:disabled)") ?? [])].filter((el) => radios.current.has(el));
  const register = useCallback((el: HTMLButtonElement, v: string) => {
    radios.current.set(el, v);
    return () => void radios.current.delete(el);
  }, []);
  // after the options have registered (their layout effects run first), and again whenever they change
  useLayoutEffect(() => {
    const list = [...(root.current?.querySelectorAll<HTMLButtonElement>(".pixilui-radio[role=radio]:not(:disabled)") ?? [])].filter((el) => radios.current.has(el));
    setFirst(list.length ? radios.current.get(list[0]!)! : null);
  }, [children, disabled]);

  const pick = useCallback(
    async (next: string) => {
      if (disabled || pending !== null || next === current) return;
      const before = current;
      if (value === undefined) setOwn(next);
      const result = onValueChange?.(next);
      if (!result || typeof (result as Promise<void>).then !== "function") return;
      setPending(next);
      try {
        await result;
      } catch {
        if (value === undefined) setOwn(before);
      } finally {
        setPending(null);
      }
    },
    [current, disabled, onValueChange, pending, value],
  );

  const keys = (event: KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    const list = enabled();
    const at = list.indexOf(document.activeElement as HTMLButtonElement);
    const step = event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : event.key === "ArrowUp" || event.key === "ArrowLeft" ? -1 : 0;
    if (at < 0 || !step || event.defaultPrevented) return;
    event.preventDefault();
    const next = list[(at + step + list.length) % list.length]!;
    void pick(radios.current.get(next)!);
    next.focus();
  };

  return (
    <GroupContext.Provider value={{ value: current, first, pick, register, name, disabled }}>
      <div
        ref={(el) => {
          root.current = el;
          if (typeof ref === "function") ref(el);
          else if (ref) ref.current = el;
        }}
        role="radiogroup"
        aria-busy={pending !== null || undefined}
        className={cn("font-body", className)}
        onKeyDown={keys}
        {...props}
      >
        {children}
        {name && current != null && <input type="hidden" name={name} value={current} />}
      </div>
    </GroupContext.Provider>
  );
});

export type RadioGroupItemProps = Omit<ComponentPropsWithoutRef<"button">, "value" | "children" | "role" | "onClick"> & {
  /** What the group reports when this option is picked. */
  value: string;
  /** The option's label: names the radio, and a click on it picks the option. */
  label: ReactNode;
  /** A second line under the label. */
  description?: ReactNode;
  /** Sets the second line in the warning color, for a choice with a cost ("No limit, it never asks"). */
  risk?: boolean;
  /** Class for the row (className goes to the radio). */
  rowClassName?: string;
};

/** One option: the radio, its label and an optional second line; the whole row clicks. */
export const RadioGroupItem = forwardRef<HTMLButtonElement, RadioGroupItemProps>(function RadioGroupItem(
  { value, label, description, risk, rowClassName, disabled, className, "aria-label": ariaLabel, ...props },
  forwarded,
) {
  const group = useContext(GroupContext);
  if (!group) throw new Error("RadioGroupItem goes inside a RadioGroup");
  const id = useId();
  const own = useRef<HTMLButtonElement | null>(null);
  const { register } = group;
  useLayoutEffect(() => (own.current ? register(own.current, value) : undefined), [register, value]);
  const picked = group.value === value;
  const focusable = picked || (group.value == null && group.first === value);
  const off = disabled || group.disabled;
  return (
    <label className={cn("pixilui-toggle-row font-body", rowClassName)}>
      <button
        ref={(el) => {
          own.current = el;
          if (typeof forwarded === "function") forwarded(el);
          else if (forwarded) forwarded.current = el;
        }}
        type="button"
        role="radio"
        aria-checked={picked ? "true" : "false"}
        aria-label={ariaLabel ?? (typeof label === "string" ? label : undefined)}
        aria-describedby={description ? `${id}-d` : undefined}
        tabIndex={off ? undefined : focusable ? 0 : -1}
        disabled={off}
        className={cn("pixilui-radio focus-visible:focus-ring", className)}
        onClick={() => void group.pick(value)}
        {...props}
      />
      <span className="pixilui-toggle-row-text">
        <b>{label}</b>
        {description && (
          <small id={`${id}-d`} data-tone={risk ? "risk" : undefined}>
            {description}
          </small>
        )}
      </span>
    </label>
  );
});
```

## Usage

When to use:

- One policy among two to five, each worth a second line: when an agent may spend, who can see a run.
- A choice where one option carries a cost, marked with risk.

When not to use:

- Several at once: use Checkbox.
- Two or three short options that switch a view: use a segmented control.
- Many options: use a select or a menu.

```tsx
import { useState } from "react";
import { RadioGroup, RadioGroupItem } from "@/components/pixilui/radio-group";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  save: ["instant", "fails"],
} as const;

/** The spending policy for every agent in a workspace; "fails" makes every save reject after 700ms so the pick goes back. */
export default function RadioGroupDemo({ save = "instant" }: KnobValues<typeof knobs>) {
  const [value, setValue] = useState("ask");
  return (
    <div className="w-full max-w-md rounded-panel bg-surface px-5 py-4 elevation-raised">
      <p id="spend-q" className="type-title text-foreground">
        When the agent wants to spend money
      </p>
      <RadioGroup
        aria-labelledby="spend-q"
        className="mt-1"
        value={value}
        onValueChange={(next) => {
          if (save !== "fails") return setValue(next);
          return new Promise<void>((_, reject) => setTimeout(() => reject(new Error("Not saved")), 700));
        }}
      >
        <RadioGroupItem value="ask" label="Ask me every time" description="Nothing is spent without your OK" />
        <RadioGroupItem value="50" label="Allow up to $50 a day" description="Then it asks before spending more" />
        <RadioGroupItem value="always" label="Always allow" description="No limit, it never asks" risk />
        <RadioGroupItem value="team" label="Use the team budget" description="Needs the Team plan" disabled />
      </RadioGroup>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` | `string` |  | The group's accessible name: the question the options answer. |
| `children` | `ReactNode` |  | RadioGroupItem rows. |
| `value` | `string \| null` |  | Controlled: the picked value. |
| `defaultValue` | `string \| null` | `null` | Uncontrolled: the value picked on the first render. |
| `onValueChange` | `(value: string) => void \| Promise<void>` |  | Runs with the new pick. Return a promise to save first: the group is aria-busy until it settles, and the pick goes back if it rejects. |
| `name` | `string` |  | A form field name: a hidden input carries the picked value. |
| `disabled` | `boolean` |  | Disables every option. |

Also accepts every native `<div>` attribute except `onChange`, `defaultValue`, `role`, and a ref to it.

## Keyboard

- `Tab`: Moves into the group on the picked option (or the first that can be picked), and out again.
- `ArrowDown` + `ArrowRight`: Picks the next option that can be picked, wrapping to the first.
- `ArrowUp` + `ArrowLeft`: Picks the previous option that can be picked, wrapping to the last.

## Accessibility

- A role="radiogroup" named by its aria-label; each option is a button with role="radio" and aria-checked.
- Each option is named by its label and described by its second line; the row is a label, so a click on the words picks it.
- Roving tabindex: one option takes focus, and disabled options are skipped.
- While a returned promise is pending the group is aria-busy.

## Motion

- Picked, the candy glass cross-fades in over 200ms and the white bead springs in over 260ms on the pop curve.
- Press scales the radio to .9; hover previews a faint bead.
- Reduced motion: no transitions, the bead shown at once.

## Responsive

- The radio is 14px at every width; the words wrap beside it, the radio on the first line.

## Performance

- The look and motion are CSS in the foundation (section 8); the bead is a pseudo-element.

## Notes for AI

- <RadioGroup aria-label="When the agent wants to spend money" value={v} onValueChange={setV}> with <RadioGroupItem value="ask" label="Ask me every time" description="..." /> rows.
- risk sets an option's second line in the warning color; disabled skips it in the keys.
- Return a promise from onValueChange to save: the pick shows at once and goes back if it rejects.
- Pass name to send the picked value with a native form.

## Related

- [Checkbox](https://pixilui.com/components/checkbox/markdown): A glass checkbox whose tick draws itself, with a mixed state for a parent, rows that click anywhere, and a save that can fail and put itself back.
- [Switch](https://pixilui.com/components/switch/markdown): A glass switch for a setting that takes effect at once: the capsule knob springs across, turns into a clear lens while held, and puts itself back if the save fails.
- [Segmented control](https://pixilui.com/components/segmented-control/markdown): One choice from two to five on a grey track: the picked pill slides to your next pick, its words changing color as it passes, and a time-boxed option says when it ends and switches back.
