APG Patterns
日本語 GitHub
日本語 GitHub

Radio Group

A set of checkable buttons where only one can be checked at a time.

🤖 AI Implementation Guide

Demo

Basic Radio Group

Use arrow keys to navigate and select. Tab moves focus in/out of the group.

With Default Value

Pre-selected option using the defaultValue prop.

With Disabled Option

Disabled options are skipped during keyboard navigation.

Horizontal Orientation

Horizontal layout with orientation="horizontal".

Native HTML

Use Native HTML First

Before using this custom component, consider using native <input type="radio"> elements with <fieldset> and <legend>. They provide built-in accessibility, work without JavaScript, and require no ARIA attributes.

<fieldset>
  <legend>Favorite color</legend>
  <label><input type="radio" name="color" value="red" /> Red</label>
  <label><input type="radio" name="color" value="blue" /> Blue</label>
  <label><input type="radio" name="color" value="green" /> Green</label>
</fieldset>

Use custom implementations when you need consistent cross-browser keyboard behavior or custom styling that native elements cannot provide.

Use Case Native HTML Custom Implementation
Basic form input Recommended Not needed
JavaScript disabled support Works natively Requires fallback
Arrow key navigation Browser-dependent* Consistent behavior
Custom styling Limited (browser-dependent) Full control
Form submission Built-in Requires hidden input

*Native radio keyboard behavior varies between browsers. Some browsers may not support all APG keyboard interactions (like Home/End) out of the box.

Accessibility Features

WAI-ARIA Roles

Role Element Description
radiogroup Container element Groups radio buttons together. Must have an accessible name via aria-label or aria-labelledby.
radio Each option element Identifies the element as a radio button. Only one radio in a group can be checked at a time.

This implementation uses custom role="radiogroup" and role="radio" for consistent cross-browser keyboard behavior. Native <input type="radio"> provides these roles implicitly.

WAI-ARIA States

aria-checked

Indicates the current checked state of the radio button. Only one radio in a group should have aria-checked="true".

Values true | false
Required Yes (on each radio)
Change Trigger Click, Space, Arrow keys

aria-disabled

Indicates that the radio button is not interactive and cannot be selected.

Values true (only when disabled)
Required No (only when disabled)
Effect Skipped during arrow key navigation, cannot be selected

WAI-ARIA Properties

aria-orientation

Indicates the orientation of the radio group. Vertical is the default.

Values horizontal | vertical (default)
Required No (only set when horizontal)
Note This implementation supports all arrow keys regardless of orientation

Keyboard Support

Key Action
Tab Move focus into the group (to selected or first radio)
Shift + Tab Move focus out of the group
Space Select the focused radio (does not unselect)
Arrow Down / Right Move to next radio and select (wraps to first)
Arrow Up / Left Move to previous radio and select (wraps to last)
Home Move to first radio and select
End Move to last radio and select

Note: Unlike Checkbox, arrow keys both move focus AND change selection. Disabled radios are skipped during navigation.

Focus Management (Roving Tabindex)

Radio groups use roving tabindex to manage focus. Only one radio in the group is tabbable at any time:

  • Selected radio has tabindex="0"
  • If none selected, first enabled radio has tabindex="0"
  • All other radios have tabindex="-1"
  • Disabled radios always have tabindex="-1"

Accessible Naming

Both the radio group and individual radios must have accessible names:

  • Radio group - Use aria-label or aria-labelledby on the container
  • Individual radios - Each radio is labeled by its visible text content via aria-labelledby
  • Native alternative - Use <fieldset> with <legend> for group labeling

Visual Design

This implementation follows WCAG 1.4.1 (Use of Color) by not relying solely on color to indicate state:

  • Filled circle - Indicates selected state
  • Empty circle - Indicates unselected state
  • Reduced opacity - Indicates disabled state
  • Forced colors mode - Uses system colors for accessibility in Windows High Contrast Mode

References

Source Code

RadioGroup.astro
---
/**
 * APG Radio Group Pattern - Astro Implementation
 *
 * A set of checkable buttons where only one can be checked at a time.
 * Uses Web Components for keyboard navigation and focus management.
 *
 * @see https://www.w3.org/WAI/ARIA/apg/patterns/radio/
 */

export interface RadioOption {
  id: string;
  label: string;
  value: string;
  disabled?: boolean;
}

export interface Props {
  /** Radio options */
  options: RadioOption[];
  /** Group name for form submission */
  name: string;
  /** Accessible label for the group */
  'aria-label'?: string;
  /** Reference to external label */
  'aria-labelledby'?: string;
  /** Initially selected value */
  defaultValue?: string;
  /** Orientation of the group */
  orientation?: 'horizontal' | 'vertical';
  /** Additional CSS class */
  class?: string;
}

const {
  options,
  name,
  'aria-label': ariaLabel,
  'aria-labelledby': ariaLabelledby,
  defaultValue = '',
  orientation = 'vertical',
  class: className = '',
} = Astro.props;

// Generate unique ID
const instanceId = `radio-group-${Math.random().toString(36).slice(2, 9)}`;

// Find initial selected value
const getInitialValue = () => {
  if (defaultValue) {
    const option = options.find((opt) => opt.value === defaultValue);
    if (option && !option.disabled) {
      return defaultValue;
    }
  }
  return '';
};

const initialValue = getInitialValue();

// Get tabbable value
const getTabbableValue = () => {
  if (initialValue) {
    return initialValue;
  }
  const firstEnabled = options.find((opt) => !opt.disabled);
  return firstEnabled?.value || '';
};

const tabbableValue = getTabbableValue();
---

<apg-radio-group
  class={`apg-radio-group ${className}`.trim()}
  role="radiogroup"
  aria-label={ariaLabel}
  aria-labelledby={ariaLabelledby}
  aria-orientation={orientation === 'horizontal' ? 'horizontal' : undefined}
  data-name={name}
  data-value={initialValue}
>
  <!-- Hidden input for form submission -->
  <input type="hidden" name={name} value={initialValue} />

  {
    options.map((option) => {
      const isSelected = initialValue === option.value;
      const isTabbable = option.value === tabbableValue && !option.disabled;
      const tabIndex = option.disabled ? -1 : isTabbable ? 0 : -1;

      return (
        <div
          role="radio"
          aria-checked={isSelected ? 'true' : 'false'}
          aria-disabled={option.disabled ? 'true' : undefined}
          aria-labelledby={`${instanceId}-label-${option.id}`}
          tabindex={tabIndex}
          data-value={option.value}
          data-disabled={option.disabled ? 'true' : undefined}
          class={`apg-radio ${isSelected ? 'apg-radio--selected' : ''} ${option.disabled ? 'apg-radio--disabled' : ''}`}
        >
          <span class="apg-radio-control" aria-hidden="true">
            <span class="apg-radio-indicator" />
          </span>
          <span id={`${instanceId}-label-${option.id}`} class="apg-radio-label">
            {option.label}
          </span>
        </div>
      );
    })
  }
</apg-radio-group>

<script>
  class ApgRadioGroup extends HTMLElement {
    private radios: HTMLElement[] = [];
    private hiddenInput: HTMLInputElement | null = null;
    private rafId: number | null = null;

    connectedCallback() {
      this.rafId = requestAnimationFrame(() => this.initialize());
    }

    private initialize() {
      this.rafId = null;
      this.radios = Array.from(this.querySelectorAll('[role="radio"]'));
      this.hiddenInput = this.querySelector('input[type="hidden"]');

      this.radios.forEach((radio) => {
        radio.addEventListener('click', this.handleClick);
        radio.addEventListener('keydown', this.handleKeyDown);
      });
    }

    disconnectedCallback() {
      if (this.rafId !== null) {
        cancelAnimationFrame(this.rafId);
        this.rafId = null;
      }
      this.radios.forEach((radio) => {
        radio.removeEventListener('click', this.handleClick);
        radio.removeEventListener('keydown', this.handleKeyDown);
      });
      this.radios = [];
      this.hiddenInput = null;
    }

    private getEnabledRadios(): HTMLElement[] {
      return this.radios.filter((radio) => radio.dataset.disabled !== 'true');
    }

    private selectRadio(radio: HTMLElement) {
      if (radio.dataset.disabled === 'true') return;

      const value = radio.dataset.value || '';

      // Update all radios
      this.radios.forEach((r) => {
        const isSelected = r === radio;
        r.setAttribute('aria-checked', isSelected ? 'true' : 'false');
        r.classList.toggle('apg-radio--selected', isSelected);

        // Update tabindex (roving)
        if (r.dataset.disabled !== 'true') {
          r.setAttribute('tabindex', isSelected ? '0' : '-1');
        }
      });

      // Update hidden input
      if (this.hiddenInput) {
        this.hiddenInput.value = value;
      }

      // Dispatch event
      this.dispatchEvent(
        new CustomEvent('valuechange', {
          detail: { value },
          bubbles: true,
        })
      );
    }

    private focusRadio(radio: HTMLElement) {
      radio.focus();
    }

    private navigateAndSelect(direction: 'next' | 'prev' | 'first' | 'last') {
      const enabledRadios = this.getEnabledRadios();
      if (enabledRadios.length === 0) return;

      const currentIndex = enabledRadios.findIndex((r) => r === document.activeElement);

      let targetIndex: number;
      switch (direction) {
        case 'next':
          targetIndex = currentIndex >= 0 ? (currentIndex + 1) % enabledRadios.length : 0;
          break;
        case 'prev':
          targetIndex =
            currentIndex >= 0
              ? (currentIndex - 1 + enabledRadios.length) % enabledRadios.length
              : enabledRadios.length - 1;
          break;
        case 'first':
          targetIndex = 0;
          break;
        case 'last':
          targetIndex = enabledRadios.length - 1;
          break;
      }

      const targetRadio = enabledRadios[targetIndex];
      if (targetRadio) {
        this.focusRadio(targetRadio);
        this.selectRadio(targetRadio);
      }
    }

    private handleClick = (event: Event) => {
      const radio = event.currentTarget as HTMLElement;
      if (radio.dataset.disabled !== 'true') {
        this.focusRadio(radio);
        this.selectRadio(radio);
      }
    };

    private handleKeyDown = (event: KeyboardEvent) => {
      const radio = event.currentTarget as HTMLElement;
      const { key } = event;

      switch (key) {
        case 'ArrowDown':
        case 'ArrowRight':
          event.preventDefault();
          this.navigateAndSelect('next');
          break;

        case 'ArrowUp':
        case 'ArrowLeft':
          event.preventDefault();
          this.navigateAndSelect('prev');
          break;

        case 'Home':
          event.preventDefault();
          this.navigateAndSelect('first');
          break;

        case 'End':
          event.preventDefault();
          this.navigateAndSelect('last');
          break;

        case ' ':
          event.preventDefault();
          this.selectRadio(radio);
          break;
      }
    };
  }

  if (!customElements.get('apg-radio-group')) {
    customElements.define('apg-radio-group', ApgRadioGroup);
  }
</script>

Usage

Example
---
import RadioGroup from './RadioGroup.astro';

const options = [
  { id: 'red', label: 'Red', value: 'red' },
  { id: 'blue', label: 'Blue', value: 'blue' },
  { id: 'green', label: 'Green', value: 'green' },
];
---

<RadioGroup
  options={options}
  name="color"
  aria-label="Favorite color"
  defaultValue="blue"
/>

<script>
  // Listen for value changes
  document.querySelector('apg-radio-group')?.addEventListener('valuechange', (e) => {
    console.log('Selected:', e.detail.value);
  });
</script>

API

Props

Prop Type Default Description
options RadioOption[] required Array of radio options
name string required Group name for form submission
aria-label string - Accessible label for the group
aria-labelledby string - ID of labeling element
defaultValue string "" Initially selected value
orientation 'horizontal' | 'vertical' 'vertical' Layout orientation
class string - Additional CSS class

Custom Events

Event Detail Description
valuechange { value: string } Dispatched when selection changes

RadioOption

Types
interface RadioOption {
  id: string;
  label: string;
  value: string;
  disabled?: boolean;
}

Testing

Tests verify APG compliance across keyboard interaction, ARIA attributes, focus management, and accessibility requirements.

Test Categories

High Priority: APG ARIA Attributes

Test Description
role="radiogroup" Container has radiogroup role
role="radio" Each option has radio role
aria-checked Selected radio has aria-checked="true"
aria-disabled Disabled radios have aria-disabled="true"
aria-orientation Only set when horizontal (vertical is default)
accessible name Group and radios have accessible names

High Priority: APG Keyboard Interaction

Test Description
Tab focus Tab focuses selected radio (or first if none)
Tab exit Tab/Shift+Tab exits the group
Space select Space selects focused radio
Space no unselect Space does not unselect already selected radio
ArrowDown/Right Moves to next and selects
ArrowUp/Left Moves to previous and selects
Home Moves to first and selects
End Moves to last and selects
Arrow wrap Wraps from last to first and vice versa
Disabled skip Disabled radios skipped during navigation

High Priority: Focus Management (Roving Tabindex)

Test Description
tabindex="0" Selected radio has tabindex="0"
tabindex="-1" Non-selected radios have tabindex="-1"
Disabled tabindex Disabled radios have tabindex="-1"
First tabbable First enabled radio tabbable when none selected
Single tabbable Only one tabindex="0" in group at any time

Medium Priority: Form Integration

Test Description
hidden input Hidden input exists for form submission
name attribute Hidden input has correct name
value sync Hidden input value reflects selection

Medium Priority: Accessibility

Test Description
axe violations No WCAG 2.1 AA violations (via jest-axe)
selected axe No violations with selected value
disabled axe No violations with disabled option

Low Priority: Props & Behavior

Test Description
onValueChange Callback fires on selection change
defaultValue Initial selection from defaultValue
className Custom class applied to container

Testing Tools

See testing-strategy.md (opens in new tab) for full documentation.

Resources