How to use radio buttons in React
📅January 30, 2022
In this article, we will learn how to use radio buttons in React application. Here, we will take an example where we will ask you to select an option from the list using Radio Button.
Checkout more articles on ReactJS
- How to display a PDF in React
- Detect URLs in a text and convert them to a link in React
- Conditionally add attributes to React components
- How to add an icon in the react-select dropdown
- How to add a Progress Bar in React
Demo Application
Output - How to use radio buttons in React - Clue Mediator
Steps to use radio buttons in React
1. Render a list of options using radio buttons
In this example, we will provide options to choose a gender from the list. So let’s render the radio buttons for gender selection.
import React from 'react';
const genderList = [
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
{ value: "other", label: "Other" }
];
function App() {
return (
<div class="app">
<h4>Radio Buttons in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
<div class="title">Select gender from the list</div>
{genderList.map((x, i) => <label key={i}>
<input type="radio" name="gender" value={x.value}> {x.label}
</label>)}
</div>
);
}
export default App;
2. Handle an onChange event
Now it’s time to capture an `onChange` event and get the selected value to display on the screen.
import React, { useState } from 'react';
const genderList = [
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
{ value: "other", label: "Other" }
];
function App() {
const [gender, setGender] = useState(null);
const handleChange = e => {
setGender(e.target.value);
}
return (
<div class="app">
<h4>Radio Buttons in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
<div class="title">Select gender from the list</div>
{genderList.map((x, i) => <label key={i}>
<input type="radio" name="gender" value={x.value} onchange={handleChange}> {x.label}
</label>)}
<div>Selected value: {gender}</div>
</div>
);
}
export default App;
3. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂