# RadioGroup and Radio

> Native radio groups from @salmonui/inputs/radio-group in a fieldset with a legend, description, errors, orientation and the browser's own arrow-key selection.

Canonical: https://salmonui.dev/docs/inputs/radio-group

`RadioGroup` holds a set of `Radio` options. Every `Radio`
is a native `<input type="radio">` drawn with CSS; the group is a
`<fieldset role="radiogroup">` named by its `<legend>`, so the browser
provides the single Tab stop and arrow-key selection.

```tsx
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import '@salmonui/inputs/radio-group/styles.css';

<RadioGroup name="plan" label="Plan" defaultValue="pro" description="Billed monthly" required>
  <Radio value="free">Free</Radio>
  <Radio value="pro">Pro</Radio>
  <Radio value="team" disabled>Team</Radio>
</RadioGroup>
```

### Live demo: RadioGroup basics

Live demo: https://salmonui.dev/demos/inputs/radio-group-basics

A controlled RadioGroup with a description, a disabled option and a horizontal layout.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';

// A controlled group with a description and a disabled option, and a horizontal group.
export default function RadioGroupBasicsDemo() {
  const [plan, setPlan] = useState<string | null>('pro');
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <RadioGroup label="Plan" name="plan" description="Billed monthly" value={plan} onValueChange={setPlan}>
        <Radio value="free">Free</Radio>
        <Radio value="pro">Pro</Radio>
        <Radio value="team" disabled>
          Team (soon)
        </Radio>
      </RadioGroup>
      <RadioGroup label="Size" name="size" defaultValue="m" orientation="horizontal">
        <Radio value="s">S</Radio>
        <Radio value="m">M</Radio>
        <Radio value="l">L</Radio>
      </RadioGroup>
      <output>Plan: {plan}</output>
    </div>
  );
}
```

## Value

`value` / `defaultValue` / `onValueChange(value, details)` on the group;
`null` selects nothing. `details.source` is
`'pointer'`, `'touch'`, `'keyboard'` (arrow keys, Space) or `'api'`;
`details.reason` is `'select'` or `'reset'` (the owning form was reset).
To read the selected value, use the controlled `value` or
`FormData.get(name)`. Without `value` the group is uncontrolled and a form
reset restores `defaultValue`.

### Live demo: Choice events

Live demo: https://salmonui.dev/demos/inputs/choice-events

Change events of RadioGroup, Radio, Checkbox and Switch with their details, radio labels before or after the control, and standalone radios grouped by a shared native name.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Switch } from '@salmonui/inputs/switch';
import { EventLog, useEventLog } from '../../components/demo-kit';

// Change events of the choice controls, radio labels before the control and
// standalone radios grouped only by a shared native `name`.
export default function ChoiceEventsDemo() {
  const [log, push] = useEventLog(12);
  const [shipping, setShipping] = useState<string | null>('standard');
  const [standalone, setStandalone] = useState('monthly');
  return (
    <>
      <div style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}>
        <RadioGroup
          label="Shipping"
          name="ce-shipping"
          labelPlacement="start"
          value={shipping}
          onValueChange={(value, details) => {
            setShipping(value);
            push(`RadioGroup onValueChange ${JSON.stringify(value)} (${details.reason}, ${details.source})`);
          }}
        >
          <Radio value="standard">Standard, 3 to 5 days</Radio>
          <Radio value="express">Express, next day</Radio>
          <Radio value="pickup" labelPlacement="end">
            Pick up in store (label after)
          </Radio>
        </RadioGroup>
        <div role="group" aria-labelledby="ce-billing-label" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '4px 16px' }}>
          <span id="ce-billing-label" style={{ flexBasis: '100%', fontWeight: 'var(--salmon-font-weight-medium)' }}>
            Billing (standalone radios)
          </span>
          <Radio name="ce-billing" value="monthly" checked={standalone === 'monthly'} onChange={(event) => (setStandalone(event.target.value), push(`Radio onChange ${event.target.value}`))}>
            Monthly
          </Radio>
          <Radio name="ce-billing" value="yearly" checked={standalone === 'yearly'} onChange={(event) => (setStandalone(event.target.value), push(`Radio onChange ${event.target.value}`))}>
            Yearly
          </Radio>
        </div>
        <Checkbox name="ce-terms" value="accepted" onCheckedChange={(checked, details) => push(`Checkbox onCheckedChange ${checked} (${details.source})`)}>
          I accept the terms
        </Checkbox>
        <Switch name="ce-dark" value="on" onCheckedChange={(checked, details) => push(`Switch onCheckedChange ${checked} (${details.source})`)}>
          Dark receipts
        </Switch>
      </div>
      <p className="demo-status">
        Shipping {JSON.stringify(shipping)} · Billing {JSON.stringify(standalone)}
      </p>
      <EventLog entries={log} label="Change events" />
    </>
  );
}
```

## Name and submission

All radios share the group's `name`; the checked one submits `name=value`.
Without `name` the radios share a generated name (needed for
native grouping) and carry `form=""`, so nothing is submitted under it;
give the group a `name` to submit it. `form` and `required` are forwarded to
every radio.

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Labels and layout

- `Radio` children are its label, in a real `<label for>`.
- `labelPlacement: 'start' | 'end'` on the group or one radio.
- `orientation: 'vertical' | 'horizontal'` (horizontal wraps).
- `label`, `description`, `errorMessage` and `invalid` on the group:
the fieldset is `aria-labelledby` the legend and
  `aria-describedby` the description and the error, with `aria-invalid` and
  `aria-required` while relevant.

## Disabled and read-only

`disabled` on a `Radio` or on the group (the fieldset is disabled).
`readOnly` keeps the radios focusable but ignores changes; the group carries
`aria-readonly`.

## Standalone radios

A `Radio` outside a `RadioGroup` is a plain native radio grouped by its own
`name`, with native `checked` / `defaultChecked`.

## Keyboard

| Key | Action |
| --- | --- |
| Tab / Shift+Tab | Enters and leaves the group (one tab stop: the checked radio, or the first) |
| Arrow Down / Arrow Right | Selects the next radio, skipping disabled ones, wrapping |
| Arrow Up / Arrow Left | Selects the previous radio |
| Space | Selects the focused radio |

In right-to-left content the browser mirrors Arrow Left and Arrow Right.
Screen readers hear "radio, n of m" with the group's legend.
Try it in the [keyboard demo](https://salmonui.dev/demos/inputs/inputs-keyboard).

## SSR

The radios are native inputs, so the server markup is the final markup:
ids come from `useId`, the checked radio is checked before hydration and
the group submits with its form without JavaScript.

The shared field behavior (labels, descriptions, validation) is described
on [Field](https://salmonui.dev/docs/inputs/field#design-notes).

## API

### RadioGroup

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `string \| null` | `null` |
| `onValueChange` | `(value, { source, reason }) => void` | |
| `name`, `form` | `string` | generated name, not submitted |
| `label`, `description`, `errorMessage`, `invalid`, `validation`, `validateOn` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `required`, `disabled`, `readOnly` | `boolean` | `false` |
| `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` |
| `labelPlacement` | `'start' \| 'end'` | `'end'` |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` |
| `classNames` | `{ label, items, description, error }` | |
| `ref` | `HTMLFieldSetElement` | |

### Radio

| Prop | Type | Default |
| --- | --- | --- |
| `value` | `string` (required) | |
| `children` | `ReactNode` (label) | |
| `labelPlacement` | `'start' \| 'end'` | the group's |
| `disabled` and other native props | native | |
| `classNames` | `{ input, label }` | |
| `ref` | `HTMLInputElement` | |

Full signatures: [`@salmonui/inputs/radio-group` API reference](https://salmonui.dev/docs/reference/inputs/radio-group).
