Radio Buttons in React

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Radio Buttons in React

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Radio Inputs in React

As a web developer you will inevitably use the radio button, and specifically use them with labels and in a radio button group.

Creating a radio button group with labels in React is demonstrated below. Here's a neat cheatsheet:

  • loop over items we want to render, and create inputs of type='radio' wiring its id, checked and onChange props to some state.
  • group the radio elements by using the input's name prop.
  • create labels with htmlFor=<input.id> prop.
App.tsx
import { useState } from "react";
import "./App.css";

export default function App() {
const items: { value: string; label: string }[] = [
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
{ value: "other", label: "Other" },
];
const [value, setValue] = useState<string | null>(null);

return (
<>
{items.map((item) => (
<div key={item.value}>
<input
name="gender"
type="radio"
value={item.value}
id={item.value}
checked={value === item.value}
onChange={(e) => setValue(e.target.value)}
/>{" "}
<label htmlFor={item.value}>{item.label}</label>
</div>
))}
</>
);
}

Creating a Custom Radio Button Group Component

Here's a sample for creating a custom radio group component

RadioGroup.tsx
App.tsx
type RadioProps = {
name: string,
items: { value: string, label: string }[],
value: string | null,
onChange: (value: string) => void,
};

export function RadioGroup({ name, items, value, onChange }: RadioProps) {
return (<>
{items.map(item => (
<div key={item.value}>
<input
name={name}
type="radio"
value={item.value}
id={name + item.value}
checked={value === item.value}
onChange={e => onChange(e.target.value)}
/> <label htmlFor={name + item.value}>{item.label}</label>
</div>
))}
</>);
}

Note: radio groups should generally only be used for values that you consider required. This is because browsers don't allow users to unset the value. If you want an optional radio group you can consider adding an option for value: unknown as we have done in the above example.

{ value: "unknown", label: "Prefer not to say" },
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

In this lesson, not only will we look at how to use the radio input component in React and type script, but also look at often overlooked general best practices for using the radio button in the browser independent of your framework of choice. And of course, these best practices also hold true for React. So let's go. Radio button is no more than a glorified input element with type radio. And you can see in its unchecked state, it shows up as a nice circle. Of course, we can use the checked attribute to force it into its check state, which is a full circle

00:34

or force it into its unchecked state, which is of course that blank circle that we saw before. And if we get rid of the checked attribute, the component is not controlled by React. And instead it's controlled by user interactions and the user can click it to move it from unchecked to the checked state. A radio is almost never used by itself and instead it is a part of a multi-choice group. So let's take a look at how we can establish this grouping of multiple radio inputs. If you just drop in multiple input elements of type radio, they're not going to be grouped by the browser by default,

01:06

which means that they are completely independent. You can actually select all of them if you wanted to do so. The way a grouping is established between multiple radio inputs is by using the name attribute. If you pass in the same name for the different inputs, they are then established to be a part of the same group. And now as we play around with the inputs, you can see that only one of them can be selected at a time. Of course, radio inputs without text are pretty useless. So let's look at some labeling best practices for radio inputs.

01:38

Before we provide a label, we need to provide a background value for what that label is going to represent. So let's add a value to all the three inputs and display a label after the input. It's common to create the label as verbose as it is needed to be for the user to understand it, but for the value to be more back and focused and short. Now, I've seen people write code like this and it does look like we have radio buttons with labels next to them, but these are not real labels. In fact, if you click on the text, it is not trigger a selection of the associated radio input.

02:13

And of course, the reason is that we haven't declared any such association. And the way you do that is by assigning an ID to the input element and then wrapping whatever text that you want to display for that radio within an HTML label element. And then we create the association between the label and the radio by providing a value for the HTML four attribute to be the same as the ID for the input that we want this label to be associated with. So let's repeat this process for the other inputs as well. Providing an ID of female and a label HT ml four female

02:48

and then repeat the same process for the other radio input. Now with these associations between the inputs and the label elements created, clicking on the label will automatically select The associated radio input as well. Now that we've established how radio inputs work within the browser, let's look at how we can manage their state with React. Now, with React in general, instead of repeating the same element code again and again, you should try and derive it from some simple JavaScript objects. For our radio inputs, the only thing that's different

03:21

between the different instances is the value and the display label. So let's store them as a simple JavaScript array of value label objects and we will store the value of the currently selected radio input with a simple use state variable. And then we simply map through the array of items and render out different diffs containing the input with the different values wired to the input and the label rendered by the label elements. Next, we create that link between the input and the label with the ID and the HTM HTML four props

03:55

and then to identify if the input is checked or not. We see if the selected value matches item value. Now, when the user clicks on an input on change will get called, at which point we will update the current value from the event target value. Similar to how you would do with the standard input element beyond the props that we've already talked about. There is really the key which needs to be unique for each item in the array, which we simply wire to item value the name, which establishes the grouping between the different input elements which we set to gender, and of course the type radio

04:28

because that is the type that we are discussing. And that's pretty much it. That's how you can use radio inputs within React. We can interact with the different labels or we can click the inputs directly if you wanted to and to see that the current value is being changed within React. Let's just add a console log statement. We will log out the value. We start off with value now, but as you select the different radio inputs, the value updates, the component read renders and it behaves the way how you would expect. Now that we understand how a radio group component can be used in React, let's make our lives easier by creating a custom

05:03

reusable radio group component. Thinking back at the common things that are being used within the rendering of the component, here are the variables that we might want to change. We create them as radio props. It is the name of the group, it is the items with value and label. It is the currently selected value. And there is of course on change which we will invoke if the user interacts with the particular radio. We create a custom component called radio group and de structured the props from the parameter and then rendered out the same thing that we saw before. We loop over the items, map them to divs

05:38

with the different inputs and the different labels with of course, the correct use of the past in props. One minor change that we make over here is that because an HTML page can have only one globally unique id, and we don't want one label from a radio group going and changing some other just because The ID got repeated, we are going to concatenate the name of the group before the ID to make it a bit more unique for a particular page. And of course, because this is how the label gets linked to the input, we will do the same for the HTML four prop

06:11

of the label as well. So with this simple radio group component, let's look at how we can use it within our application. We bring in the radio group component from the module radio group where we just created it. And then we have the same items and the use state value that we had before. But within the rendering will be render out the radio group pass in a name, which in our case is going to be gender, the items, the value, and the on change. And this is sort of a testament of the beauty of react. You can find a common pattern, move it into a common component,

06:43

and then reuse it as much as you want. And in terms of behavior, if you run our application, it behaves exactly as it was doing before. If you have the different radio groups, the labels work, the inputs work, and yes, everything works. One thing to know about radio buttons is that the user has no way of uns selecting a value. So you should only use a radio group if it is a required field. So once the user has selected one of these inputs, for example, they select female, then they can't really just unselect it, clicking it again does nothing. They can click the other ones,

07:15

but they will always have to select one of these values. So if you are using radio inputs, always provide the user with at least one option that makes sense for them, and you can use another option to let the user opt out as well. For example, value unknown with the label. Prefer not to say so, even though the user cannot unselect an option, they can select this one to opt out. I'll wrap things up there. As always, thank you for joining me and I will see you in the next one.