Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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:
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:
Property
Description
type="radio"
Specifies that the input is a radio button.
name
Groups related radio buttons together.
value
Assigns a unique value to each radio button.
checked
Determines whether the radio button is selected.
onChange
Event 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.