Table of contents
1.
Introduction
2.
Prerequisites
3.
How Do You Use Radio Buttons in React.Js?
3.1.
Create a new React component
4.
Approach
4.1.
Example
5.
Steps To Implement Radio Button In React
6.
Radio Buttons from Third-party Libraries
6.1.
Using Material-UI
7.
Radio Buttons from Third-party Libraries
7.1.
Default Selected Value
8.
React Radio Buttons API
9.
Frequently Asked Questions
9.1.
How do you handle radio button selection in React?
9.2.
Why is the name attribute important in radio buttons?
9.3.
Can we use radio buttons with Material-UI?
10.
Conclusion
Last Updated: Feb 3, 2025
Easy

Radio Button in React JS

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Radio Button in React JS is an interactive component that allows users to select one option from a group of predefined choices. It is widely used in forms, surveys, and settings where only one option is allowed at a time. React simplifies the implementation of radio buttons by making them easy to manage with state, providing an efficient way to handle user input.

Radio Button in React JS

In this article, you will learn about the syntax of Radio Button in React JS, how to create them, and best practices for using them effectively in your React applications.

Prerequisites

Before working with radio buttons in React, you should have:

  • Basic knowledge of JavaScript and React
     
  • Node.js installed on your system
     
  • A React project set up using create-react-app
     

If you haven't installed React yet, you can create a new React project using the following command:

npx create-react-app radio-button-app
cd radio-button-app
npm start

How Do You Use Radio Buttons in React.Js?

To use radio buttons in React JS, you need to follow a few steps. First, you need to create a component where the radio buttons will be placed. Then, you need to manage the state of the selected option. Finally, you need to handle the changes when a user selects a different option.

Let’s take a complete example to understand this:

Create a new React component

import React, { useState } from 'react';
function RadioButtonExample() {
  // State to hold the selected value
  const [selectedValue, setSelectedValue] = useState('');


  // Function to handle changes
  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };
  return (
    <div>
      <h1>Select Your Favorite Color</h1>
      <form>
        <label>
          <input
            type="radio"
            value="red"
            checked={selectedValue === 'red'}
            onChange={handleChange}
          />
          Red
        </label>
        <br />
        <label>
          <input
            type="radio"
            value="blue"
            checked={selectedValue === 'blue'}
            onChange={handleChange}
          />
          Blue
        </label>
        <br />
        <label>
          <input
            type="radio"
            value="green"
            checked={selectedValue === 'green'}
            onChange={handleChange}
          />
          Green
        </label>
      </form>
      <p>You selected: {selectedValue}</p>
    </div>
  );
}
export default RadioButtonExample;


In this example, we create a component called RadioButtonExample. We use the useState hook to manage the state of the selected value. The handleChange function updates the state whenever a radio button is clicked. Each radio button has a checked attribute that is set to true if its value matches the current state.

Approach

In React, radio buttons are implemented using the input element with the type="radio". Each radio button in a group should have the same name attribute to ensure only one can be selected at a time. The useState hook is used to manage the selected value.

Example

import React, { useState } from "react";
function RadioButtonExample() {
  const [selectedOption, setSelectedOption] = useState("option1");

  const handleChange = (event) => {
    setSelectedOption(event.target.value);
  };
  return (
    <div>
      <h3>Select an option:</h3>
      <label>
        <input
          type="radio"
          value="option1"
          checked={selectedOption === "option1"}
          onChange={handleChange}
        />
        Option 1
      </label>
      <br />
      <label>
        <input
          type="radio"
          value="option2"
          checked={selectedOption === "option2"}
          onChange={handleChange}
        />
        Option 2
      </label>
      <br />
      <p>Selected Option: {selectedOption}</p>
    </div>
  );
}
export default RadioButtonExample;

 

Explanation:

  • useState is used to store the selected option.
     
  • Each radio button has a value and checked attribute.
     
  • onChange updates the state when the user selects a different option.

Steps To Implement Radio Button In React

  1. Create a new React component
    • Create a file RadioButton.js.
       
    • Import useState from React.
       
  2. Define State

    • Use the useState hook to track the selected value.
       
  3. Render Radio Buttons

    • Use the input element with type="radio".
       
    • Ensure all radio buttons in a group share the same name attribute.
       
  4. Handle Change Events

    • Attach an onChange event to update the selected value.
       
  5. Display Selected Value

    • Show the currently selected option to the user.

Radio Buttons from Third-party Libraries

Instead of manually styling radio buttons, we can use third-party UI libraries like Material-UI and React Bootstrap.

Using Material-UI

Install Material-UI:

npm install @mui/material @emotion/react @emotion/styled


Example:

import React, { useState } from "react";
import { FormControl, FormLabel, RadioGroup, FormControlLabel, Radio } from "@mui/material";

function MaterialUIRadioButton() {
  const [value, setValue] = useState("option1");

  const handleChange = (event) => {
    setValue(event.target.value);
  };
  return (
    <FormControl>
      <FormLabel>Select an option</FormLabel>
      <RadioGroup value={value} onChange={handleChange}>
        <FormControlLabel value="option1" control={<Radio />} label="Option 1" />
        <FormControlLabel value="option2" control={<Radio />} label="Option 2" />
      </RadioGroup>
      <p>Selected Option: {value}</p>
    </FormControl>
  );
}
export default MaterialUIRadioButton;

 

Explanation:

  • FormControl groups related form components.
  • RadioGroup manages a set of radio buttons.
  • FormControlLabel binds labels to radio buttons.

Radio Buttons from Third-party Libraries

Using third-party libraries can make adding radio buttons to your React app easier and more visually appealing. One popular library for this is Material-UI (now called MUI). MUI provides a set of pre-styled components, including radio buttons, that follow Material Design guidelines.

Let’s see how you can use MUI’s radio buttons in your React project:

Install MUI:

First, you need to install the MUI library. Open your terminal and run the following command:

npm install @mui/material @emotion/react @emotion/styled


Create a new React component using MUI’s Radio component:

import React, { useState } from 'react';
import { Radio, RadioGroup, FormControlLabel, FormLabel } from '@mui/material';
function MuiRadioButtonExample() {
  // State to hold the selected value
  const [selectedValue, setSelectedValue] = useState('');

  // Function to handle changes
  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  return (
    <div>
      <h1>Select Your Favorite Color</h1>
      <FormLabel component="legend">Choose a color</FormLabel>
      <RadioGroup
        aria-labelledby="demo-controlled-radio-buttons-group"
        name="controlled-radio-buttons-group"
        value={selectedValue}
        onChange={handleChange}
      >
        <FormControlLabel value="red" control={<Radio />} label="Red" />
        <FormControlLabel value="blue" control={<Radio />} label="Blue" />
        <FormControlLabel value="green" control={<Radio />} label="Green" />
      </RadioGroup>
      <p>You selected: {selectedValue}</p>
    </div>
  );
}
export default MuiRadioButtonExample;


In this example, we use MUI’s Radio, RadioGroup, and FormControlLabel components. The RadioGroup component helps manage the state of the radio buttons, and FormControlLabel is used to pair each radio button with a label. This makes the radio buttons more accessible and easier to style.

Default Selected Value

Setting a default selected value for radio buttons in React JS is straightforward. You can initialize the state with a default value, and the corresponding radio button will be selected when the component mounts. Let’s see how you can set a default selected value:

Modify the state initialization:

In the previous example, we initialized the state with an empty string (''). To set a default value, you can initialize it with one of the radio button values.

import React, { useState } from 'react';
import { Radio, RadioGroup, FormControlLabel, FormLabel } from '@mui/material';

function MuiRadioButtonExample() {
  // State to hold the selected value
  const [selectedValue, setSelectedValue] = useState('blue'); // Set default value to 'blue'


  // Function to handle changes
  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  return (
    <div>
      <h1>Select Your Favorite Color</h1>
      <FormLabel component="legend">Choose a color</FormLabel>
      <RadioGroup
        aria-labelledby="demo-controlled-radio-buttons-group"
        name="controlled-radio-buttons-group"
        value={selectedValue}
        onChange={handleChange}
      >
        <FormControlLabel value="red" control={<Radio />} label="Red" />
        <FormControlLabel value="blue" control={<Radio />} label="Blue" />
        <FormControlLabel value="green" control={<Radio />} label="Green" />
      </RadioGroup>
      <p>You selected: {selectedValue}</p>
    </div>
  );
}
export default MuiRadioButtonExample;


In this example, the useState hook initializes the selectedValue state with 'blue'. When the component mounts, the radio button with the value 'blue' will be selected by default.

React Radio Buttons API

React does not have a built-in API specifically for radio buttons, but it relies on standard HTML radio button attributes. Some commonly used properties include:

PropertyDescription
type="radio"Specifies that the input is a radio button.
nameGroups related radio buttons together.
valueAssigns a unique value to each radio button.
checkedDetermines whether the radio button is selected.
onChangeEvent handler for state updates.

Frequently Asked Questions

How do you handle radio button selection in React?

You can use the useState hook to track the selected value and update it using the onChange event.

Why is the name attribute important in radio buttons?

The name attribute ensures that only one radio button in a group can be selected at a time.

Can we use radio buttons with Material-UI?

Yes, Material-UI provides a RadioGroup component that simplifies radio button implementation with built-in styling.

Conclusion

In this article, we discussed how to implement radio buttons in React using different approaches. We learned how to use useState to manage selected values, style radio buttons with third-party libraries like Material-UI, and understand the key attributes of radio buttons. 

Live masterclass