Radio group
FreeOne 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.
npx shadcn@latest add https://pixilui.com/r/radio-group.jsonPreview
The picked radio's white bead springs in.
Save
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>
);
}When to use
Use it when
- 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.
Use something else when
- 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.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/radio-group.jsonAdds radio-group.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
components/pixilui/radio-group.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>
);
});
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { RadioGroup } from "@/components/pixilui/radio-group";
<RadioGroup onValueChange={onValueChange}>Save changes</RadioGroup>The radio is 14px at every width; the words wrap beside it, the radio on the first line.
API reference
PropTypeDefault
valuestring | null–Controlled: the picked value.defaultValuestring | nullnullUncontrolled: 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.namestring–A form field name: a hidden input carries the picked value.disabledboolean–Disables every option.aria-labelstring–The group's accessible name: the question the options answer.childrenReactNode–RadioGroupItem rows.Also takes every native <div> attribute except onChange, defaultValue, role, and a ref.
Keyboard
TabMoves into the group on the picked option (or the first that can be picked), and out again.
↓ →Picks the next option that can be picked, wrapping to the first.
↑ ←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.