Back to React Spectrum

RadioGroup

packages/react-aria-components/docs/RadioGroup.mdx

2022-12-1620.0 KB
Original Source

{/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs'; export default Layout;

import docs from 'docs:react-aria-components'; import statelyDocs from 'docs:@react-stately/radio'; import typesDocs from 'docs:@react-types/shared/src/events.d.ts'; import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable, VersionBadge, ClassAPI} from '@react-spectrum/docs'; import styles from '@react-spectrum/docs/src/docs.css'; import packageData from 'react-aria-components/package.json'; import Anatomy from '/packages/react-aria/docs/radio/anatomy.svg'; import ChevronRight from '@spectrum-icons/workflow/ChevronRight'; import {Divider} from '@react-spectrum/divider'; import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard'; import {ExampleList} from '@react-spectrum/docs/src/ExampleList'; import {Keyboard} from '@react-spectrum/text'; import Label from '@react-spectrum/docs/pages/assets/component-illustrations/Label.svg'; import Form from '@react-spectrum/docs/pages/assets/component-illustrations/Form.svg'; import {StarterKits} from '@react-spectrum/docs/src/StarterKits';


category: Forms keywords: [radiobutton, radio, input, aria] type: component

RadioGroup

<PageDescription>{docs.exports.RadioGroup.description}</PageDescription>

<HeaderInfo packageData={packageData} componentNames={['RadioGroup']} sourceData={[ {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/radiobutton/'} ]} />

Example

tsx
import {RadioGroup, Radio, Label} from 'react-aria-components';

<RadioGroup>
  <Label>Favorite pet</Label>
  <Radio value="dogs">Dog</Radio>
  <Radio value="cats">Cat</Radio>
  <Radio value="dragon">Dragon</Radio>
</RadioGroup>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
@import './Button.mdx' layer(button);
@import './Form.mdx' layer(form);
css
@import "@react-aria/example-theme";

.react-aria-RadioGroup {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: var(--text-color);
}

.react-aria-Radio {
  display: flex;
  /* This is needed so the HiddenInput is positioned correctly */
  position: relative;
  align-items: center;
  gap: 0.571rem;
  font-size: 1.143rem;
  color: var(--text-color);
  forced-color-adjust: none;

  &:before {
    content: '';
    display: block;
    width: 1.286rem;
    height: 1.286rem;
    box-sizing: border-box;
    border: 0.143rem solid var(--border-color);
    background: var(--field-background);
    border-radius: 1.286rem;
    transition: all 200ms;
  }

  &[data-pressed]:before {
    border-color: var(--border-color-pressed);
  }

  &[data-selected] {
    &:before {
      border-color: var(--highlight-background);
      border-width: 0.429rem;
    }

    &[data-pressed]:before {
      border-color: var(--highlight-background-pressed);
    }
  }

  &[data-focus-visible]:before {
    outline: 2px solid var(--focus-ring-color);
    outline-offset: 2px;
  }
}
</details>

Features

Radio groups can be built in HTML with the <fieldset> and <input> elements, however these can be difficult to style. RadioGroup and Radio help achieve accessible radio groups that can be styled as needed.

  • Accessible – Radio groups are exposed to assistive technology via ARIA, and automatically associate a nested <Label>. Description and error message help text slots are supported as well.
  • HTML form integration – Each individual radio uses a visually hidden <input> element under the hood, which enables HTML form integration and autofill.
  • Validation – Support for native HTML constraint validation with customizable UI, custom validation functions, and server-side validation errors.
  • Cross-browser – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

Anatomy

<Anatomy />

A radio group consists of a set of radio buttons, and a label. Each radio includes a label and a visual selection indicator. A single radio button within the group can be selected at a time. Users may click or touch a radio button to select it, or use the <Keyboard>Tab</Keyboard> key to navigate to the group, the arrow keys to navigate within the group, and the <Keyboard>Space</Keyboard> key to select an option.

RadioGroup also supports optional description and error message elements, which can be used to provide more context about the field, and any validation messages. These are linked with the inputs via the aria-describedby attribute.

tsx
import {RadioGroup, Radio, Label, Text, FieldError, SelectionIndicator} from 'react-aria-components';

<RadioGroup>
  <Label />
  <Radio>
    <SelectionIndicator />
  </Radio>
  <Text slot="description" />
  <FieldError />
</RadioGroup>

Individual radio buttons must have a visual label. If the radio group does not have a visible label, an aria-label or aria-labelledby prop must be passed instead to identify the element to assistive technology.

Concepts

RadioGroup makes use of the following concepts:

<section className={styles.cardGroup} data-size="small">

<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">

<Form /> </ExampleCard> </section>

Composed components

A RadioGroup uses the following components, which may also be used standalone or reused in other components.

<section className={styles.cardGroup} data-size="small">

<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label" title="Label" description="A label provides context for an input element."> <Label /> </ExampleCard>

</section>

Examples

<ExampleList tag="radio" />

Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured Storybook that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="radiogroup" />

Reusable wrappers

If you will use a RadioGroup in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.

This example wraps RadioGroup and all of its children together into a single component which accepts a label prop, which is passed to the right place. It also shows how to use the description slot to render help text, and FieldError component to render validation errors.

tsx
import type {RadioGroupProps, ValidationResult} from 'react-aria-components';
import {Text, FieldError} from 'react-aria-components';

interface MyRadioGroupProps extends Omit<RadioGroupProps, 'children'> {
  children?: React.ReactNode,
  label?: string,
  description?: string,
  errorMessage?: string | ((validation: ValidationResult) => string)
}

function MyRadioGroup({
  label,
  description,
  errorMessage,
  children,
  ...props
}: MyRadioGroupProps) {
  return (
    <RadioGroup {...props}>
      <Label>{label}</Label>
      {children}
      {description && <Text slot="description">{description}</Text>}
      <FieldError>{errorMessage}</FieldError>
    </RadioGroup>
  );
}

<MyRadioGroup label="Favorite sport">
  <Radio value="soccer">Soccer</Radio>
  <Radio value="baseball">Baseball</Radio>
  <Radio value="basketball">Basketball</Radio>
</MyRadioGroup>

Value

Default value

An initial, uncontrolled value can be provided to the RadioGroup using the defaultValue prop, which accepts a value corresponding with the value prop of each Radio.

tsx
<MyRadioGroup label="Are you a wizard?" defaultValue="yes">
  <Radio value="yes">Yes</Radio>
  <Radio value="no">No</Radio>
</MyRadioGroup>

Controlled value

A controlled value can be provided using the value prop, which accepts a value corresponding with the value prop of each Radio. The onChange event is fired when the user selects a radio.

tsx
function Example() {
  let [selected, setSelected] = React.useState(null);

  return (
    <>
      <MyRadioGroup label="Favorite avatar" value={selected} onChange={setSelected}>
        <Radio value="wizard">Wizard</Radio>
        <Radio value="dragon">Dragon</Radio>
      </MyRadioGroup>
      <p>You have selected: {selected ?? ''}</p>
    </>
  );
}

HTML forms

RadioGroup supports the name prop, paired with the Radio value prop, for integration with HTML forms.

tsx
<MyRadioGroup label="Favorite pet" name="pet">
  <Radio value="dogs">Dogs</Radio>
  <Radio value="cats">Cats</Radio>
</MyRadioGroup>

Validation

RadioGroup supports the isRequired prop to ensure the user selects an option, as well as custom client and server-side validation. It can also be integrated with other form libraries. See the Forms guide to learn more.

To display validation errors, add a <FieldError> element as a child of the RadioGroup. This allows you to render error messages from all of the above sources with consistent custom styles.

tsx
import {Form, FieldError, Button} from 'react-aria-components';

<Form>
  <RadioGroup name="pet" isRequired>
    <Label>Favorite pet</Label>
    <Radio value="dogs">Dog</Radio>
    <Radio value="cats">Cat</Radio>
    <Radio value="dragon">Dragon</Radio>
    <FieldError />
  </RadioGroup>
  <Button type="submit">Submit</Button>
</Form>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-Radio {
  &[data-invalid] {
    &:before {
      border-color: var(--invalid-color);
    }

    &[data-pressed]:before {
      border-color: var(--invalid-color-pressed);
    }
  }
}

.react-aria-RadioGroup {
  .react-aria-FieldError {
    font-size: 12px;
    color: var(--invalid-color);
  }
}
</details>

By default, FieldError displays default validation messages provided by the browser. See Customizing error messages in the Forms guide to learn how to provide your own custom errors.

Description

The description slot can be used to associate additional help text with a radio group.

tsx
<RadioGroup>
  <Label>Favorite avatar</Label>
  <Radio value="wizard">Wizard</Radio>
  <Radio value="dragon">Dragon</Radio>
  <Text slot="description">Please select an avatar.</Text>
</RadioGroup>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-RadioGroup {
  [slot=description] {
    font-size: 12px;
  }
}
</details>

Orientation

RadioGroups are vertically oriented by default. The orientation prop can be used to change the orientation to horizontal.

tsx
<MyRadioGroup label="Favorite avatar" orientation="horizontal">
  <Radio value="wizard">Wizard</Radio>
  <Radio value="dragon">Dragon</Radio>
</MyRadioGroup>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-RadioGroup {
  &[data-orientation=horizontal] {
    flex-direction: row;
    align-items: center;
  }
}
</details>

Disabled

The entire RadioGroup can be disabled with the isDisabled prop.

tsx
<MyRadioGroup label="Favorite sport" isDisabled>
  <Radio value="soccer">Soccer</Radio>
  <Radio value="baseball">Baseball</Radio>
  <Radio value="basketball">Basketball</Radio>
</MyRadioGroup>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-Radio {
  &[data-disabled] {
    color: var(--text-color-disabled);

    &:before {
      border-color: var(--border-color-disabled);
    }
  }
}
</details>

To disable an individual radio, pass isDisabled to the Radio instead.

tsx
<MyRadioGroup label="Favorite sport">
  <Radio value="soccer">Soccer</Radio>
  <Radio value="baseball" isDisabled>Baseball</Radio>
  <Radio value="basketball">Basketball</Radio>
</MyRadioGroup>

Read only

The isReadOnly prop makes the selection immutable. Unlike isDisabled, the RadioGroup remains focusable. See the MDN docs for more information.

tsx
<MyRadioGroup label="Favorite avatar" defaultValue="wizard" isReadOnly>
  <Radio value="wizard">Wizard</Radio>
  <Radio value="dragon">Dragon</Radio>
</MyRadioGroup>

Props

RadioGroup

<PropTable component={docs.exports.RadioGroup} links={docs.links} />

Radio

<PropTable component={docs.exports.Radio} links={docs.links} />

Text

<Text> accepts all HTML attributes.

FieldError

A <FieldError> displays validation errors.

<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary> <PropTable component={docs.exports.FieldError} links={docs.links} /> </details>

Styling

React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName naming convention.

css
.react-aria-Radio {
  /* ... */
}

A custom className can also be specified on any component. This overrides the default className provided by React Aria with your own.

jsx
<Radio className="my-radio">
</Radio>

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

css
.react-aria-Radio[data-selected] {
  /* ... */
}

The className and style props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like Tailwind.

jsx
<Radio className={({isPressed}) => isPressed ? 'bg-gray-700' : 'bg-gray-600'} />

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the radio is selected.

jsx
<Radio>
  {({isSelected}) => (
    <>
      {isSelected && <SelectedIcon />}
      Option
    </>
  )}
</Radio>

The states and selectors for each component used in a RadioGroup are documented below.

RadioGroup

A RadioGroup can be targeted with the .react-aria-RadioGroup CSS selector, or by overriding with a custom className. It supports the following states and render props:

<StateTable properties={docs.exports.RadioGroupRenderProps.properties} />

Radio

A Radio can be targeted with the .react-aria-Radio CSS selector, or by overriding with a custom className. It supports the following states:

<StateTable properties={docs.exports.RadioRenderProps.properties} />

Text

The help text elements within a RadioGroup can be targeted with the [slot=description] and [slot=errorMessage] CSS selectors, or by adding a custom className.

FieldError

A FieldError can be targeted with the .react-aria-FieldError CSS selector, or by overriding with a custom className. It supports the following render props:

<StateTable properties={docs.exports.FieldErrorRenderProps.properties} />

Advanced customization

Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in mergeProps).

<ContextTable components={['RadioGroup', 'Radio']} docs={docs} />

This example shows a RadioDescription component that accepts a radio in its children and renders a description element below it. It uses the useId hook to generate a unique id for the description, and associates it with the radio via the aria-describedby attribute passed to the RadioContext provider.

tsx
import {RadioContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface RadioDescriptionProps {
  children?: React.ReactNode,
  description?: string
}

function RadioDescription({children, description}: RadioDescriptionProps) {
  let descriptionId = useId();
  return (
    <div>
      <RadioContext.Provider value={{'aria-describedby': descriptionId}}>
        {children}
      </RadioContext.Provider>
      <small id={descriptionId}>{description}</small>
    </div>
  );
}

<MyRadioGroup label="Show scrollbars" defaultValue="automatic">
  <RadioDescription description="Scrollbars will always be visible when using a mouse, and only while scrolling when using a trackpad.">
    <Radio value="automatic">Automatic</Radio>
  </RadioDescription>
  <RadioDescription description="Scrollbars will appear only while you are scrolling.">
    <Radio value="scrolling">While scrolling</Radio>
  </RadioDescription>
  <RadioDescription description="Scrollbars will always be visible.">
    <Radio value="always">Always</Radio>
  </RadioDescription>
</MyRadioGroup>

Custom children

RadioGroup passes props to its child components, such as the label, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.

<ContextTable components={['Label', 'Text']} docs={docs} />

This example consumes from LabelContext in an existing styled label component to make it compatible with React Aria Components. The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by RadioGroup.

tsx
import type {LabelProps} from 'react-aria-components';
import {LabelContext, useContextProps} from 'react-aria-components';

const MyCustomLabel = React.forwardRef((props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, LabelContext);
  ///- end highlight -///

  // ... your existing Label component
  return <label {...props} ref={ref} />;
});

Now you can use MyCustomLabel within a RadioGroup, in place of the builtin React Aria Components Label.

tsx
<RadioGroup>
  <MyCustomLabel>Favorite pet</MyCustomLabel>
  <Radio value="dogs">Dog</Radio>
  <Radio value="cats">Cat</Radio>
  <Radio value="dragon">Dragon</Radio>
</RadioGroup>

State

RadioGroup provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.RadioGroupState} /> object to its children via RadioGroupStateContext. This can be used to access and manipulate the radio group's state.

Hooks

If you need to customize things further, such as accessing internal state or customizing DOM structure, you can drop down to the lower level Hook-based API. See useRadioGroup for more details.