Skip to main content

Radio

Headless radio component for creating mutually exclusive selections in forms and interactive UIs.

Live Demo​

This demo shows the recommended pattern: a Field wrapper supplies the group label, helper text, and error message — all wired to the radiogroup via coordinated ARIA IDs — while each Radio.Item carries its own visible label. Setting invalid on Field.Root cascades to the radiogroup as aria-invalid and renders the Field.ErrorMessage.

JavaScript
<Field.Root className='radio-demo-container'>
<Field.Label className='group-label'>Subscription plan</Field.Label>
<Radio.Root name='plan' className='radio-group'>
  <Radio.Item value='basic' className='radio-item'>
    <span className='radio-text'>Basic</span>
  </Radio.Item>
  <Radio.Item value='pro' className='radio-item'>
    <span className='radio-text'>Pro</span>
  </Radio.Item>
  <Radio.Item value='enterprise' className='radio-item'>
    <span className='radio-text'>Enterprise</span>
  </Radio.Item>
</Radio.Root>
<Field.Description className='description'>
  Pick the plan that best fits your team.
</Field.Description>
<Field.ErrorMessage className='error'>
  Please select a plan
</Field.ErrorMessage>
</Field.Root>

Features​

  • ✅ Mutually exclusive selection within radio groups
  • ✅ Controlled and uncontrolled state management
  • ✅ Form integration through a visually hidden native radio input per item
  • ✅ Group-level and item-level disabled states
  • ✅ Configurable orientation (vertical / horizontal)
  • ✅ Configurable selection behavior with selectOnFocus
  • ✅ Polymorphic rendering with as prop

Import​

import { Radio } from '@turkish-technology/spar';

Anatomy​

The Radio component is built as a compound component with two main parts:

Parts
RootState and keyboard interaction container
ItemIndividual radio option

Structure​

<Radio.Root>
<Radio.Item />
<Radio.Item />
<Radio.Item />
</Radio.Root>

Alias Note: Radio and Radio.Root are the same component — pick whichever import style fits your project.

import { Radio } from '@turkish-technology/spar';

<Radio.Root>
<Radio.Item />
<Radio.Item />
<Radio.Item />
</Radio.Root>;

Data Flow:

  • Radio.Root manages selected value and provides context
  • Each enabled Radio.Item registers itself for index-based focus navigation (in DOM order)
  • Radio.Item renders a <span role="radio"> by default; its text content is the radio's accessible name
  • Each Radio.Item renders its own visually hidden input[type="radio"] for form compatibility — the selected value reaches form data exactly once
  • Consumer onKeyDown / onFocus / onBlur (root) and onClick / onKeyDown / onFocus (item) run before the built-in behavior; calling event.preventDefault() in a consumer handler skips the built-in navigation or selection for that event

Code Examples​

Basic Controlled Radio Group​

Control the selected value from parent state when the chosen option affects other parts of the UI.

function ControlledRadio() {
const [selectedValue, setSelectedValue] = React.useState('medium');

return (
<Radio.Root
value={selectedValue}
onChange={setSelectedValue}
aria-label="Size selection"
>
<Radio.Item value="small">Small</Radio.Item>
<Radio.Item value="medium">Medium</Radio.Item>
<Radio.Item value="large">Large</Radio.Item>
</Radio.Root>
);
}

Uncontrolled Radio Group with Default Value​

Use defaultValue when the group should start with a selection but does not need ongoing external state management.

function UncontrolledRadio() {
const handleValueChange = (value: string) => {
console.log('Selected:', value);
};

return (
<Radio.Root
defaultValue="silver"
onChange={handleValueChange}
aria-label="Membership tier"
>
<Radio.Item value="bronze">Bronze Membership</Radio.Item>
<Radio.Item value="silver">Silver Membership</Radio.Item>
<Radio.Item value="gold">Gold Membership</Radio.Item>
</Radio.Root>
);
}

Horizontal Orientation​

Switch to horizontal orientation for toolbars, segmented controls, or compact inline choices.

function HorizontalRadio() {
const [alignment, setAlignment] = React.useState('left');

return (
<Radio.Root
value={alignment}
onChange={setAlignment}
orientation="horizontal"
aria-label="Text alignment"
>
<Radio.Item value="left">Left</Radio.Item>
<Radio.Item value="center">Center</Radio.Item>
<Radio.Item value="right">Right</Radio.Item>
</Radio.Root>
);
}

Disabled Items and Groups​

Disable individual options when they are temporarily unavailable while keeping the rest of the group interactive.

function DisabledRadio() {
const [plan, setPlan] = React.useState('basic');

return (
<Radio.Root value={plan} onChange={setPlan} aria-label="Subscription plan">
<Radio.Item value="free">Free Plan</Radio.Item>
<Radio.Item value="basic">Basic Plan</Radio.Item>
<Radio.Item value="premium" disabled>
Premium Plan (Coming Soon)
</Radio.Item>
</Radio.Root>
);
}

Toolbar Radio Group​

Set selectOnFocus={false} in toolbar patterns so arrow keys move focus without immediately changing the current selection.

function ToolbarRadio() {
const [alignment, setAlignment] = React.useState('left');

return (
<div role="toolbar" aria-label="Text formatting">
<Radio.Root
value={alignment}
onChange={setAlignment}
selectOnFocus={false}
orientation="horizontal"
aria-label="Text alignment"
>
<Radio.Item value="left">Align Left</Radio.Item>
<Radio.Item value="center">Align Center</Radio.Item>
<Radio.Item value="right">Align Right</Radio.Item>
<Radio.Item value="justify">Justify</Radio.Item>
</Radio.Root>
{/* Other toolbar controls */}
</div>
);
}

Form Integration​

Add name when the selected value should be submitted through a native HTML form.

function FormRadio() {
const [paymentMethod, setPaymentMethod] = React.useState('credit');

const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
console.log('Payment method:', formData.get('payment'));
};

return (
<form onSubmit={handleSubmit}>
<Radio.Root
value={paymentMethod}
onChange={setPaymentMethod}
name="payment"
required
aria-label="Payment method"
>
<Radio.Item value="credit">Credit Card</Radio.Item>
<Radio.Item value="debit">Debit Card</Radio.Item>
<Radio.Item value="paypal">PayPal</Radio.Item>
<Radio.Item value="bank">Bank Transfer</Radio.Item>
</Radio.Root>
<button type="submit">Continue</button>
</form>
);
}

Custom Elements with Polymorphic API​

Use the polymorphic API when the group or items need to match an existing semantic wrapper or layout structure.

function CustomRadio() {
const [theme, setTheme] = React.useState('light');

return (
<Radio.Root
value={theme}
onChange={setTheme}
as="fieldset"
aria-label="Theme selection"
>
<legend>Choose Theme</legend>
<Radio.Item value="light" as="div">
Light Theme
</Radio.Item>
<Radio.Item value="dark" as="div">
Dark Theme
</Radio.Item>
<Radio.Item value="auto" as="div">
Auto Theme
</Radio.Item>
</Radio.Root>
);
}

API Reference​

Radio / Radio.Root​

Root container that manages selection state, registration, and keyboard behavior. Radio and Radio.Root are the same component - the difference is only import/notation style.

Props

NameTypeDefaultDescription
id?stringundefinedBase id used when generating fallback form name
value?stringundefinedControlled selected value
defaultValue?stringundefinedUncontrolled initial value
onChange?(value: string) => voidundefinedSelection change handler
name?stringundefinedForm key for the items' native radio inputs (fallback: ${id}-radio-group or useId()-radio-group)
disabled?booleanfalseDisables entire radio group
readOnly?booleanfalseRead-only state. Group can be inspected but value cannot change; inherited from Field
required?booleanfalseMarks group as required for forms
invalid?booleanfalseMarks group as invalid (aria-invalid); inherited from Field
orientation?'horizontal' | 'vertical''vertical'Layout direction for keyboard navigation
selectOnFocus?booleantrueWhether arrow keys automatically select the focused item
autoFocus?booleanfalseWhether to focus the first focusable item on mount
aria-label?stringundefinedAccessible name for the group
aria-labelledby?stringundefinedReferences element that labels the group
aria-describedby?stringundefinedReferences element that describes the group
as?React.ElementType'div'Polymorphic root element
children?React.ReactNodeundefinedRadio.Item components

Events

NameParametersDescriptionWhen Triggered
onChange(value: string)Selection state changes (fires only when the value actually changes)User selects a different radio item
onKeyDown(event: React.KeyboardEvent)Runs before the internal navigation handler; preventDefault() skips Arrow/Home/End handlingKey pressed inside the group
onFocus(event: React.FocusEvent)Runs before the internal focus syncRoot or an item receives focus (root then initializes focusedValue)
onBlur(event: React.FocusEvent)Runs before the internal focus resetFocus leaves the root or an item

HTML Attributes

AttributeValuePurpose
role"radiogroup"Identifies root as a radio group
aria-requiredtruePresent when required is true
aria-readonlytruePresent when readOnly is true
aria-invalidtruePresent when invalid is true
data-orientation"horizontal" | "vertical"Indicates layout direction
data-disabled""Present when group disabled
data-readonly""Present when group is read-only
data-required""Present when group is required
data-invalid""Present when group is invalid
data-select-on-focus""Present when selectOnFocus is true
data-autofocus""Present when autoFocus is true

Radio.Item​

Individual option inside Radio.Root. Renders a <span role="radio"> by default whose text content is the radio's accessible name. Use as for another element that may carry role="radio" — not <label>, which allows no ARIA role.

Props

NameTypeDefaultDescription
valuestring-Unique identifier for this radio option
disabled?booleanfalseDisables this specific radio item
aria-label?stringundefinedAccessible name when children insufficient
aria-describedby?stringundefinedReferences element that describes this item
as?React.ElementType'span'Polymorphic root element
children?React.ReactNode | ((state: RadioItemRenderProps) => React.ReactNode)undefinedLabel content or render props function

Render Props (RadioItemRenderProps)

PropertyTypeDescription
isCheckedbooleanWhether this radio item is currently selected
disabledbooleanWhether this radio item is disabled
isFocusedbooleanWhether this radio item currently has focus
select() => voidFunction to programmatically select this radio item

Events

NameParametersDescriptionWhen Triggered
onClick(event: React.MouseEvent)Runs before the internal selection; preventDefault() skips selectingItem is clicked
onKeyDown(event: React.KeyboardEvent)Runs before the internal key handler; preventDefault() skips selectingFocused item receives Space or Enter
onFocus(event: React.FocusEvent)Runs before the internal focus trackingItem receives focus

HTML Attributes

AttributeValuePurpose
role"radio"Identifies interactive radio item
aria-checkedbooleanReflects checked state
aria-disabledtruePresent when item is disabled
data-state"checked" | "unchecked"Indicates selection state
data-disabled""Present when item disabled
data-focus""Present when item has focus
data-readonly""Present when group is read-only
tabIndex0 | -1Manages focus with roving tabindex

Internal Hidden Input (Radio.Item)

Each Radio.Item renders a sibling <input type="radio"> for form submission and native HTML5 validation. The element is hidden via inline style={visuallyHidden} (a 1px-clipped sr-only style), so consumers do not need to add CSS to suppress it.

AttributeValuePurpose
type"radio"Native radio semantics for forms
namestringComes from Radio.Root context
valuestringItem value
checkedbooleanMirrors item checked state
disabledbooleanTrue when root or item is disabled
requiredbooleanTrue when group/Field marks the selection as required (browsers treat required on radios as group-level by name)
tabIndex-1Excludes hidden input from tab order
aria-hidden"true"Keeps the hidden input out of the AT tree — the visible role="radio" element owns assistive semantics
onChangeno-opSilences React's controlled-input warning; the visible role="radio" element owns interaction
stylevisuallyHiddenInline 1px-clipped style applied by the headless package itself

Keyboard Interactions​

Keyboard behavior implemented by Radio.Root and Radio.Item:

KeyActionContextNotes
TabMoves focus into the current tab stop in the groupTabbing into groupInitial tab stop is driven by each item's computed tabIndex
Shift + TabMoves focus out of the groupTabbing backwardBrowser default behavior
ArrowDownMoves focus to next item (wraps)orientation="vertical"Also selects when selectOnFocus={true}
ArrowUpMoves focus to previous item (wraps)orientation="vertical"Also selects when selectOnFocus={true}
ArrowRightMoves focus to next item (wraps)orientation="horizontal"Also selects when selectOnFocus={true}
ArrowLeftMoves focus to previous item (wraps)orientation="horizontal"Also selects when selectOnFocus={true}
HomeMoves focus to first itemAny orientationAlso selects when selectOnFocus={true}
EndMoves focus to last itemAny orientationAlso selects when selectOnFocus={true}
SpaceSelects focused itemOn Radio.ItemCalls internal click/select logic
EnterSelects focused itemOn Radio.ItemCalls internal click/select logic

Notes:

  • ArrowUp / ArrowDown do not navigate in horizontal mode.
  • ArrowLeft / ArrowRight do not navigate in vertical mode.
  • Disabled items are skipped by arrow / Home / End navigation and keep their DOM position when re-enabled.
  • In a readOnly group arrow keys and Home / End still move focus but never change the value.