Frontend Recipes

Radio

Radio and RadioGroup. One selection from a set — and the option set should be small enough to see all at once.

A radio is a hard square that fills with a square dot when selected, rather than a circle. It is the most visibly unusual decision in the library, and it is intentional: a round radio in a system with no other curve reads as a leftover from a different design.

Copy source

Styling

Requires: Nothing. Any bundler that understands .module.css.

This is the component, complete. Copy the files below into a ui/ folder at your project root and keep the folder structure — the imports between them are relative, so the paths have to come along. Each component imports its own .module.css, so its class names are scoped to it and cannot collide with your application's.

ui/components/Radio/Radio.tsx
tsx
import { createContext, useContext, useId, useMemo } from "react";
import { cx } from "../../internal/cx";
import { fieldStyles } from "../../internal/Field";
import controlStyles from "../../internal/control.module.css";
import {
  useControllableState,
  type ControllableState,
} from "../../internal/useControllableState";
import styles from "./radio.module.css";

interface RadioGroupContextValue {
  name: string;
  value: string | undefined;
  setValue: (next: string) => void;
  disabled: boolean;
}

const RadioGroupContext = createContext<RadioGroupContextValue | null>(null);

export interface RadioGroupProps
  extends Omit<
    React.FieldsetHTMLAttributes<HTMLFieldSetElement>,
    "onChange" | "defaultValue"
  > {
  /** Shared name for the group; generated if omitted. */
  name?: string;
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  label?: string;
  hint?: string;
  error?: string;
  disabled?: boolean;
  /** Lays the options out horizontally instead of stacked. */
  direction?: "vertical" | "horizontal";
}

// Native radios under one shared name already provide arrow-key navigation, so
// the group owns only state and the fieldset semantics.
export function RadioGroup({
  name,
  value,
  defaultValue = "",
  onValueChange,
  label,
  hint,
  error,
  disabled = false,
  direction = "vertical",
  className,
  children,
  ...rest
}: RadioGroupProps): React.JSX.Element {
  const state: ControllableState<string> = useControllableState({
    value,
    defaultValue,
    onChange: onValueChange,
  });

  const generatedName = useId();
  const resolvedName = name ?? `fr-radio-group-${generatedName}`;

  const contextValue = useMemo<RadioGroupContextValue>(
    () => ({
      name: resolvedName,
      value: state.value,
      setValue: state.setValue,
      disabled,
    }),
    [resolvedName, state.value, state.setValue, disabled],
  );

  return (
    <RadioGroupContext.Provider value={contextValue}>
      <fieldset
        className={cx(styles.group, className)}
        disabled={disabled}
        aria-invalid={error !== undefined ? true : undefined}
        {...rest}
      >
        {label ? <legend className={fieldStyles.label}>{label}</legend> : null}
        {hint ? <p className={fieldStyles.hint}>{hint}</p> : null}
        <div
          className={cx(
            styles.items,
            direction === "horizontal" && styles.itemsHorizontal,
          )}
        >
          {children}
        </div>
        {error ? (
          <p className={fieldStyles.error} role="alert">
            {error}
          </p>
        ) : null}
      </fieldset>
    </RadioGroupContext.Provider>
  );
}

export interface RadioProps
  extends Omit<React.ComponentProps<"input">, "type" | "value"> {
  label: string;
  /** Required when the radio is not inside a RadioGroup. */
  value: string;
  hint?: string;
}

// Inside a RadioGroup this inherits name, checked, and disabled from the group.
export function Radio({
  label,
  value,
  hint,
  className,
  name,
  checked,
  onChange,
  disabled,
  ref,
  ...rest
}: RadioProps): React.JSX.Element {
  const group = useContext(RadioGroupContext);
  const isDisabled = disabled ?? group?.disabled ?? false;

  const inputProps: React.InputHTMLAttributes<HTMLInputElement> = group
    ? {
        name: group.name,
        checked: group.value === value,
        onChange: () => group.setValue(value),
      }
    : { name, checked, onChange };

  return (
    <label className={cx(styles.radio, className)}>
      <input
        ref={ref}
        type="radio"
        value={value}
        className={cx(controlStyles.nativeCheck, styles.input)}
        disabled={isDisabled}
        {...inputProps}
        {...rest}
      />
      <span className={styles.body}>
        <span className={styles.label}>{label}</span>
        {hint ? <span className={fieldStyles.hint}>{hint}</span> : null}
      </span>
    </label>
  );
}
ui/components/Radio/radio.module.css
css
/* Radio — a square that fills with an ink dot when selected.
   Deliberately square: a round radio would break the geometry of the system. */

.group {
  display: flex;
  flex-direction: column;
  gap: var(--fr-space-2);
  margin: 0;
  padding: 0;
  border: 0;
  min-width: 0;
}

.items {
  display: flex;
  flex-direction: column;
  gap: var(--fr-space-2);
  padding: 0;
  margin-top: var(--fr-space-1);
}

.itemsHorizontal {
  flex-direction: row;
  flex-wrap: wrap;
  gap: var(--fr-space-5);
}

.group > legend {
  padding: 0;
  margin-bottom: var(--fr-space-1);
}

.radio {
  display: flex;
  align-items: flex-start;
  gap: var(--fr-space-2);
  cursor: pointer;
}

.input {
  border-radius: var(--fr-radius);
  margin-top: 0.1875rem;
}

.input:checked {
  border-color: var(--fr-ink);
}

.input:checked::after {
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  background: var(--fr-ink);
}

.input:focus-visible {
  outline: var(--fr-focus-width) solid var(--fr-accent);
  outline-offset: var(--fr-focus-offset);
}

.input:hover:not(:disabled):not(:checked) {
  border-color: var(--fr-accent);
}

.radio:has(.input:disabled) {
  cursor: not-allowed;
}

.input:disabled + .body {
  color: var(--fr-disabled-ink);
}

.body {
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.label {
  font-size: var(--fr-text-body);
  line-height: 1.5;
  color: var(--fr-ink);
}
ui/internal/cx.ts
ts
export type ClassValue = string | false | null | undefined;

// The only part of `clsx` this library needs, without the dependency.
export function cx(...values: ClassValue[]): string {
  const out: string[] = [];
  for (const value of values) {
    if (value) out.push(value);
  }
  return out.join(" ");
}
ui/internal/Field.tsx
tsx
import { createContext, useContext, useId, useMemo } from "react";
import styles from "./field.module.css";
import { cx } from "./cx";

interface FieldContextValue {
  controlId: string;
  describedBy: string | undefined;
  invalid: boolean;
  required: boolean;
  disabled: boolean;
}

const FieldContext = createContext<FieldContextValue | null>(null);

// Controls read their ids from the enclosing <Field> instead of rebuilding the
// label/hint/error wiring; null when used standalone.
export function useFieldContext(): FieldContextValue | null {
  return useContext(FieldContext);
}

export interface FieldProps {
  /** Visible label. Always rendered — a control without a name is a bug. */
  label: string;
  /** Supplemental guidance, announced via aria-describedby. */
  hint?: string;
  /** When present the control becomes invalid and this text is announced. */
  error?: string;
  /** Marks the control as required and shows a marker next to the label. */
  required?: boolean;
  disabled?: boolean;
  /** Renders the optional badge. Ignored when `required` is set. */
  optional?: boolean;
  /** Hides the label visually but keeps it for assistive technology. */
  hideLabel?: boolean;
  id?: string;
  className?: string;
  children: React.ReactNode;
}

export function Field({
  label,
  hint,
  error,
  required = false,
  disabled = false,
  optional = false,
  hideLabel = false,
  id,
  className,
  children,
}: FieldProps): React.JSX.Element {
  const generatedId = useId();
  const controlId = id ?? `fr-field-${generatedId}`;
  const hintId = `${controlId}-hint`;
  const errorId = `${controlId}-error`;

  const describedBy = useMemo(() => {
    const ids: string[] = [];
    if (hint) ids.push(hintId);
    if (error) ids.push(errorId);
    return ids.length > 0 ? ids.join(" ") : undefined;
  }, [hint, error, hintId, errorId]);

  const contextValue = useMemo<FieldContextValue>(
    () => ({
      controlId,
      describedBy,
      invalid: Boolean(error),
      required,
      disabled,
    }),
    [controlId, describedBy, error, required, disabled],
  );

  return (
    <FieldContext.Provider value={contextValue}>
      <div className={cx(styles.field, className)}>
        <label
          className={cx(styles.label, hideLabel && styles.visuallyHidden)}
          htmlFor={controlId}
        >
          {label}
          {required ? (
            <span aria-hidden="true" className={styles.required}>
              *
            </span>
          ) : optional ? (
            <span className={styles.optional}>Optional</span>
          ) : null}
        </label>

        {children}

        {hint && !error ? (
          <p className={styles.hint} id={hintId}>
            {hint}
          </p>
        ) : null}
        {error ? (
          <p className={styles.error} id={errorId} role="alert">
            {error}
          </p>
        ) : null}
      </div>
    </FieldContext.Provider>
  );
}

/** Field classes a control outside this file needs — the hint and the error. */
export const fieldStyles = styles;
ui/internal/useControllableState.ts
ts
import { useCallback, useEffect, useRef, useState } from "react";

export interface UseControllableStateOptions<T> {
  value?: T;
  defaultValue: T;
  onChange?: (next: T) => void;
}

export interface ControllableState<T> {
  value: T;
  setValue: (next: T | ((prev: T) => T)) => void;
}

// Two functional updates in one tick both resolve against the committed value,
// so the second wins; pass `value` if you need batched updates.
export function useControllableState<T>({
  value,
  defaultValue,
  onChange,
}: UseControllableStateOptions<T>): ControllableState<T> {
  const isControlled = value !== undefined;
  const [uncontrolled, setUncontrolled] = useState<T>(defaultValue);
  const current = isControlled ? value : uncontrolled;

  const onChangeRef = useRef(onChange);
  // Assigned in an effect, never during render, so `setValue` can stay stable.
  useEffect(() => {
    onChangeRef.current = onChange;
  });

  const setValue = useCallback(
    (next: T | ((prev: T) => T)) => {
      const resolved = isUpdater(next) ? next(current) : next;
      if (Object.is(resolved, current)) return;
      if (!isControlled) setUncontrolled(resolved);
      onChangeRef.current?.(resolved);
    },
    [current, isControlled],
  );

  return { value: current, setValue };
}

// `typeof x === "function"` does not narrow a union that includes `T` when `T`
// could itself be callable, so the guard states that case and leaves the rest.
function isUpdater<T>(value: T | ((prev: T) => T)): value is (prev: T) => T {
  return typeof value === "function";
}

Every component reads from these two files. Copy them once, on your first component, and reuse them thereafter.

ui/styles/tokens.css
css
/* Every ground is white and every value below cleared AA on it; dark mode
   re-derives rather than inverting. Check contrast again before changing a value. */

:root {
  /* The only radius token. Do not override per component. */
  --fr-radius: 0px;

  /* Core surfaces — flat by default; separation comes from rules, not fills. */
  --fr-paper: #ffffff;
  --fr-surface: #ffffff;
  --fr-surface-sunken: #f5f5f5;
  --fr-ink: #262626;
  --fr-ink-muted: #525252;
  --fr-ink-subtle: #737373;

  /* Rules — soft divides, rule bounds, strong marks a control edge. A boundary
     is a hairline tone; only controls and active markers earn the ink one. */
  --fr-rule: #e5e5e5;
  --fr-rule-strong: #262626;
  --fr-rule-soft: #ededed;

  /* Accent: Emerald. Reserved for interaction, never decoration. `bright` is
     ornament only — marks and arrows, never a label or a fill that carries one. */
  --fr-accent: #047857;
  --fr-accent-ink: #ffffff;
  --fr-accent-soft: #ecfdf5;
  --fr-accent-hover: #065f46;
  --fr-accent-bright: #10b981;

  /* Status. Success stays a true green rather than a second emerald, so a badge
     tone never reads as the accent. */
  --fr-danger: #a81f24;
  --fr-danger-soft: #fbeaeb;
  --fr-danger-ink: #ffffff;
  --fr-success: #15803d;
  --fr-success-soft: #f0fdf4;
  --fr-success-ink: #ffffff;
  --fr-warning: #7a5312;
  --fr-warning-soft: #f8efdf;
  --fr-warning-ink: #ffffff;

  /* Inverse surfaces */
  --fr-inverse-surface: #262626;
  --fr-inverse-ink: #ffffff;

  /* Disabled */
  --fr-disabled-surface: #f0f0f0;
  --fr-disabled-ink: #737373;

  /* Hard shadow: no blur, ever. */
  --fr-shadow-hard: 3px 3px 0 var(--fr-rule-strong);
  --fr-shadow-hard-sm: 2px 2px 0 var(--fr-rule-strong);

  /* No font ships with the library, so this is the platform's own UI face. */
  --fr-font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue",
    Arial, sans-serif;
  --fr-font-mono: ui-monospace, "SF Mono", "Menlo", "Consolas", monospace;

  --fr-text-display: 3.5rem;
  --fr-text-h1: 2.5rem;
  --fr-text-h2: 1.75rem;
  --fr-text-h3: 1.25rem;
  --fr-text-body: 0.9375rem;
  --fr-text-small: 0.8125rem;
  --fr-text-micro: 0.6875rem;

  --fr-leading-display: 1.02;
  --fr-leading-heading: 1.15;
  --fr-leading-body: 1.6;
  --fr-tracking-micro: 0.08em;
  --fr-tracking-display: -0.02em;

  --fr-weight-regular: 400;
  --fr-weight-medium: 500;
  --fr-weight-semibold: 600;
  --fr-weight-bold: 700;

  /* Spacing scale — 4px base */
  --fr-space-0: 0;
  --fr-space-1: 0.25rem;
  --fr-space-2: 0.5rem;
  --fr-space-3: 0.75rem;
  --fr-space-4: 1rem;
  --fr-space-5: 1.5rem;
  --fr-space-6: 2rem;
  --fr-space-7: 3rem;
  --fr-space-8: 4rem;
  --fr-space-9: 6rem;

  /* Sizing */
  --fr-control-sm: 1.75rem;
  --fr-control-md: 2.25rem;
  --fr-control-lg: 2.75rem;
  --fr-rule-width: 1px;
  --fr-rule-width-strong: 2px;
  --fr-focus-width: 2px;
  --fr-focus-offset: 2px;

  /* Motion — short and linear; this library does not bounce. */
  --fr-duration-fast: 90ms;
  --fr-duration-base: 140ms;
  --fr-ease: cubic-bezier(0.2, 0, 0, 1);

  /* Layers */
  --fr-z-sticky: 10;
  --fr-z-overlay: 100;
  --fr-z-dialog: 101;

  /* Layout */
  --fr-container: 78rem;
  --fr-measure: 68ch;
}

/* Dark re-derives rather than inverting: the ground stays near-black and the
   accent lifts so it still clears AA (#34D399 on #0A0A0A is 10.33:1). */
[data-theme="dark"] {
  --fr-paper: #0a0a0a;
  --fr-surface: #141414;
  --fr-surface-sunken: #1c1c1c;
  --fr-ink: #f5f5f5;
  --fr-ink-muted: #a3a3a3;
  --fr-ink-subtle: #7a7a7a;

  --fr-rule: #3a3a3a;
  --fr-rule-strong: #f5f5f5;
  --fr-rule-soft: #2a2a2a;

  --fr-accent: #34d399;
  --fr-accent-ink: #022c22;
  --fr-accent-soft: #052e22;
  --fr-accent-hover: #6ee7b7;
  --fr-accent-bright: #34d399;

  --fr-danger: #fca5a5;
  --fr-danger-soft: #2e1214;
  --fr-danger-ink: #240708;
  --fr-success: #86efac;
  --fr-success-soft: #0d2415;
  --fr-success-ink: #04150c;
  --fr-warning: #e2b262;
  --fr-warning-soft: #2a2011;
  --fr-warning-ink: #1c1305;

  --fr-inverse-surface: #f5f5f5;
  --fr-inverse-ink: #0a0a0a;

  --fr-disabled-surface: #1f1f1f;
  --fr-disabled-ink: #6a6a6a;

  --fr-shadow-hard: 3px 3px 0 #f5f5f5;
  --fr-shadow-hard-sm: 2px 2px 0 #f5f5f5;
}

/* Opt-in inverse region: use for a closing band or a deliberate contrast strip. */
[data-theme="inverse"] {
  --fr-paper: #171717;
  --fr-surface: #171717;
  --fr-surface-sunken: #242424;
  --fr-ink: #ffffff;
  --fr-ink-muted: #b5b5b5;
  --fr-ink-subtle: #8a8a8a;
  --fr-rule: #3d3d3d;
  --fr-rule-strong: #ffffff;
  --fr-rule-soft: #2e2e2e;
  --fr-accent: #34d399;
  --fr-accent-ink: #022c22;
  --fr-accent-soft: #052e22;
  --fr-accent-hover: #6ee7b7;
  --fr-accent-bright: #34d399;
  --fr-inverse-surface: #ffffff;
  --fr-inverse-ink: #171717;
  --fr-shadow-hard: 3px 3px 0 #ffffff;
  --fr-shadow-hard-sm: 2px 2px 0 #ffffff;
}

@media (prefers-reduced-motion: reduce) {
  :root {
    --fr-duration-fast: 0ms;
    --fr-duration-base: 0ms;
  }
}
ui/styles/base.css
css
/* Only what a module cannot scope: the page reset. Everything a component owns
   lives in its .module.css, so no global class here can collide with yours. */

*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  -webkit-text-size-adjust: 100%;
  text-size-adjust: 100%;
}

body {
  margin: 0;
  font-family: var(--fr-font-sans);
  font-size: var(--fr-text-body);
  line-height: var(--fr-leading-body);
  color: var(--fr-ink);
  background: var(--fr-paper);
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

h1,
h2,
h3,
h4,
h5,
h6,
p,
figure,
blockquote,
dl,
dd {
  margin: 0;
}

ul,
ol {
  margin: 0;
  padding: 0;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-weight: var(--fr-weight-semibold);
  line-height: var(--fr-leading-heading);
  letter-spacing: -0.02em;
  text-wrap: balance;
}

a {
  color: var(--fr-accent);
  text-decoration-thickness: 1px;
  text-underline-offset: 2px;
}

a:hover {
  color: var(--fr-accent-hover);
}

img,
svg,
video,
canvas {
  display: block;
  max-width: 100%;
}

button,
input,
select,
textarea {
  font: inherit;
  color: inherit;
  letter-spacing: inherit;
}

Then import the component from its file. A page that holds state needs "use client".

css
/* app/layout.tsx — once, before your own CSS */
import "../ui/styles/tokens.css";
import "../ui/styles/base.css";
tsx
// app/page.tsx
"use client";

import { RadioGroup, Radio } from "../ui/components/Radio/Radio";

Basic

A radio group with per-option hints
Plan

Change at any time.

RadioGroup owns the shared name and the controlled/uncontrolled value. You do not pass name to the individual radios — pass it once to the group, or let it generate one.

Horizontal

A short, inline group
Billing period

Horizontal layout works for two or three short options. Beyond that the options stop reading as a set.

States

Disabled group and error
Disabled group
With an error

Disabling the group disables every radio inside it, because disabled is set on the <fieldset>. That is one of the reasons the group renders a fieldset rather than a div.

Props

RadioGroup

PropTypeDefaultDescription
labelstring—Rendered as the fieldset legend.
valuestring—Controlled value. Omit to use defaultValue.
defaultValuestring''Initial value when uncontrolled.
onValueChange(value: string) => void—Called with the newly selected value.
namestring—Shared radio name. Generated if omitted.
disabledbooleanfalseDisables the fieldset, and every radio in it.
direction'vertical' | 'horizontal'verticalLayout of the options.
hintstring—Help text beneath the legend.
errorstring—Error text, rendered in a role=alert region.
RadioGroup props

Radio

PropTypeDefaultDescription
value*string—The value this option represents.
label*string—Visible label for the option.
hintstring—Secondary line under the label, per option.
disabledboolean—Overrides the group's disabled state for this option.
Radio props

Accessibility

  • The group is a <fieldset> with a <legend>, so the question is announced with each option. This is why label is on the group, not repeated on every radio.
  • Radios share a name, so the browser gives you arrow-key navigation within the group and roving focus — none of which is reimplemented here.
  • Disabling the group sets disabled on the fieldset, which correctly disables all children at the platform level.
  • The visual is appearance: none, but selection is real: the value submits with the form, and assistive technology reports "selected".
  • Focus is the standard 2px accent ring.

Do and don't

DoUse radios when all options should be visible for comparison.
Don’tUse radios for more than a handful of options.
DoPut the group label on the group, once.
Don’tUse a radio for an on/off toggle. Use Switch or a single Checkbox.