---
label: RadioGroup
---

import LibraryInfo from '@theme/LibraryInfo'
import { Feedback, TokensTable, PropsTable } from '../../src/components'
import { RadioGroup } from '@telus-uds/components-web'
import { RadioGroup as BaseDocs } from 'docs/@telus-uds/components-base'
import AvailableOnBoth from '../../partials/_platform-considerations-both.mdx'
import NoStylisticVariants from '../../partials/_variants-none.mdx'

# RadioGroup

<LibraryInfo figmaLink="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2F4zJn2Qn6uXOqPP1GVDipy6%2F%25F0%259F%258D%2580-Allium-Components%3Fnode-id%3D458%253A458" />

```jsx live
<RadioGroup
  items={[
    {
      label: 'First item',
      id: 'first'
    },
    {
      label: 'Second item',
      id: 'second'
    },
    {
      label: 'Third item',
      id: 'third'
    }
  ]}
/>
```

## Introduction

A RadioGroup renders a group of [Radio](radio) buttons in a list, with
a text label for each radio button. Exactly one radio button may be selected at a time.

[Follow the appropriate instructions](importing-components) to add this component in to your app.

## Guidance

Use RadioGroup where the user needs to select one item from multiple options, and where those
options can be explained simply with one short phrase (generally, up to around 5 words).

### Alternatives

- If the options require information beyond one short phrase, consider
  [RadioCardGroup](radio-card-group)
- If the options are very simple and can be described in one or two words or numbers, consider
  [ButtonGroup](button-group)
- If it should be possible to select more than one item at a time, consider
  [CheckboxGroup](checkbox-group)

### Rationale for vertical display

At this time, `RadioGroup` is intended to vertically display items to allow users to easily scan available options and make a selection:

- Sighted humans are conditioned to scan top-to-bottom in a document (whether printed or on screen)
- Additionally, low-vision users benefit from having vertically stacked radio buttons
- Low vision users that rely on screen magnification would also find the vertical option preferable
- If you place a series of radio buttons or checkboxes horizontally, the user could skip past some of the options to the right, especially if there is a wide gap of white space between them
- Additionally, horizontal radio buttons also create a challenge when options are of different lengths or are too close to each other which adds cognitive load to discern between them

Additional resources:

- [Radio buttons: vertical or horizontal thread on WebAIM](https://webaim.org/discussion/mail_thread?thread=5541)
- [Radio Buttons in UX Design](https://babich.biz/radio-buttons-ux-design/)

Should you have a need for alternative layouts, please [reach out to the UDS team](https://www.telus.com/universal-design-system/help).

### Labeling the group

Three props are available for labelling the group to users:

- `legend` sets the main title for the group and should be a short, simple name for what the user
  is to choose.
- `hint` is an optional short sentence clarifying the `legend` to help users understand what choice they are
  being asked to make and what the result of their choice will be.
- `tooltip` allows further clarifying information to be included but not shown by default, only shown
  on pressing a [TooltipButton](tooltip). This should be used for information
  that will help many users make a choice, but which is not needed by all users.

```jsx live
<RadioGroup
  legend="Data allowance"
  hint="Choose a monthly internet data limit"
  tooltip="Amounts are listed in GB (gigabytes). 1 GB is roughly 40 minutes of Blu-ray quality video."
  items={[
    {
      label: '20 GB, with 10 GB first month bonus',
      id: '20'
    },
    {
      label: '30 GB, with 20 GB first month bonus',
      id: '30'
    },
    {
      label: '40 GB, with 30 GB first month bonus',
      id: '40'
    }
  ]}
/>
```

### Items

Use the `items` prop to pass an array of objects describing each Radio in the group:

- `label`: text displayed alongside the radio button
- `id`: identifier used to store which Radio is selected (uses index if undefined). This is
  written into HTML as an id attr on web, so should be unique and not match IDs used elsewhere on a page.
- `onChange`: optional function called on selection, in addition to updating the group's selection state

```jsx live
<RadioGroup
  items={[
    {
      label: 'First item',
      id: 'first'
    },
    {
      label: 'Second item',
      id: 'second'
    },
    {
      label: 'Third item',
      id: 'third',
      onChange: (value, event) =>
        console.log('Third item selected', value, event.currentTarget, event)
    }
  ]}
/>
```

### Controlled

The selection state may be controlled by a parent by passing `checkedId` and an `onChange`
function that updates the parent's state. If the component is controlled in this way,
`checkedId` must never be undefined; pass `null` or an empty string if there is no selection.

```jsx live
function ControlledRadioButtonGroup() {
  const [checkedId, setCheckedId] = useState('')
  return (
    <StackView space={3}>
      <Typography>Currently selected: "{checkedId}"</Typography>
      <RadioGroup
        checkedId={checkedId}
        onChange={setCheckedId}
        items={[
          { label: 'First item', id: 'first' },
          { label: 'Second item', id: 'second' },
          { label: 'Third item', id: 'third' }
        ]}
      />
    </StackView>
  )
}
```

### Uncontrolled

If `checkedId` is not provided, RadioGroup manages its own state. An initial selection may
be provided by passing `initialCheckedId`.

```jsx live
<RadioGroup
  initialCheckedId="Second item"
  items={[
    { label: 'First item', id: 'first' },
    { label: 'Second item', id: 'second' },
    { label: 'Third item', id: 'third' }
  ]}
/>
```

### `onChange` functions

The `onChange` handler for RadioGroup may be used in both controlled and uncontrolled usage and
takes two arguments: `value` (string) and `event` (React SyntheticEvent object).

The `event` object shape varies between web and native applications, and type of user interaction.
It is usually more stable to have application logic respond to the `value` and not `event` properties.

On web, `event.currentTarget` will point to the accessible container that holds the radio role and
state, and should be used if accessing the raw HTML element is required (`event.target` will vary
on mouse clicks depending on where exactly the click occured).

```jsx live
<RadioGroup
  onChange={(value, event) => console.log(value, event.currentTarget, event)}
  items={[
    { label: 'First item', id: 'first' },
    { label: 'Second item', id: 'second' },
    { label: 'Third item', id: 'third' }
  ]}
/>
```

### Adding React elements in the Items

You also can use the `label` prop to pass a React element and display it accompanied by a text or not.
When including images as part of the label, please ensure that it is readable and it makes sense when announced by screen readers.

```jsx live
<RadioGroup
  items={[
    {
      label: (
        <div style={{ display: 'flex' }}>
          <Icon icon={Icons.Visa} /> ending in 7011
        </div>
      ),
      id: 'first'
    },
    {
      label: 'MasterCard credit card ending in 8012',
      id: 'second'
    },
    {
      label: 'American Express credit card ending in 9013',
      id: 'third'
    }
  ]}
/>
```

### Use in forms

For web forms, the `name` prop may be used to define the name of the group's `fieldset` and input
elements, and `legend` may be used to provide a title with `legend` type for the fieldset.

```jsx live
<RadioGroup
  legend="Choose a product"
  name="product-choice"
  items={[
    { label: 'First product', id: 'first' },
    { label: 'Second product', id: 'second' },
    { label: 'Third product', id: 'third' }
  ]}
/>
```

### Validation

Validation state may be set by passing 'error' or 'success' to the `validation` prop.

```jsx live
function ValidationExample() {
  const [validation, setValidation] = useState(null)
  const validate = (id) => setValidation(['a', 'c'].includes(id) ? 'success' : 'error')
  return (
    <RadioGroup
      legend="Choose 'a' or 'c'"
      onChange={validate}
      validation={validation}
      feedback={validation && `${validation === 'success' ? 'Valid' : 'Invalid'} item chosen.`}
      items={[
        { label: "Option 'a'", id: 'a' },
        { label: "Option 'b'", id: 'b' },
        { label: "Option 'c'", id: 'c' },
        { label: "Option 'd'", id: 'd' }
      ]}
    />
  )
}
```

### A11y guidelines

RadioGroup accepts all the common accessibility props, but also sets accessibility role `radiogroup`
and controls the accessibility state of children like Radio and Feedback based on current state.

### Platform considerations

<AvailableOnBoth />

## Props

<PropsTable base={BaseDocs} />

## Tokens

<TokensTable base={BaseDocs} component="RadioGroup" tokensProps={['tokens', 'radioTokens']} />

## Variants

<NoStylisticVariants />

## Feedback

<Feedback component="RadioGroup" />
