Radio

Import
import { Radio, RadioGroup } from "reshaped";
import type { RadioProps, RadioGroupProps } from "reshaped";
Related components
Storybook
Full keyboard navigation
Can be controlled and uncontrolled
Supports radio groups with custom rendering


Usage

Radio component works like native radio buttons, which means you can either use its value property to define what will be passed to the form when it's submitted.

Like all native inputs in React, Radio supports controlled and uncontrolled options. It becomes controlled when you use checked property, which means you have to control it with your state. An uncontrolled variant is used when you use the defaultChecked property, which lets you define the default state and allow the browser to control the rest afterward.

Note: You shouldn't be using both properties simultaneously, and React will throw a warning if that happens.

Since Radio is an exclusive selection - you can't deselect a checked item unless you select another one with the same name.

States

If there is an error related to the radio field, you can use a hasError flag. Usually, you would do this only when displaying a group of radio buttons, and you can likely use RadioGroup component for that instead.

To make Radio non-interactive, you can use the disabled flag. Like in native radio buttons, it will prevent the onChange handler from triggering.

Note: Disabled state fades the component content. Even though it's not required to have a regular contrast ratio for disabled elements, make not to use it over a gray background.

Composition

Most of the time, you will be rendering groups of radio buttons, which you can do with the RadioGroup component. It handles the selection of radio buttons and lets you receive the current value of the group. At the same time, it doesn't enforce any specific layout, so you're free to use any layout components.

As you can see, name and onChange properties apply to all Radio components within its scope. You will get the currently selected value logged into the console by choosing a specific Radio.

In the same way, Radio can define its checked value, RadioGroup supports value and defaultValue to control the selection in the options list.

If you need to provide a label for a group of radio buttons, you can use the FormControl utility with the group flag turned on. That will resolve FormControl HTML tags correctly for a group of input fields.

Both Radio and RadioGroup support content composition. Since RadioGroup doesn't provide any markup, you can use it with any layout components. For the Radio component, you can render multiple elements as its children.

Accessibility

  • When using Radio without children, wrap it with a label element.
Previous
Next