How to use radio buttons in React
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
Demo Application
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import React from 'react'; const genderList = [ { value: "male", label: "Male" }, { value: "female", label: "Female" }, { value: "other", label: "Other" } ]; function App() { return ( <div className="app"> <h4>Radio Buttons in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <div className='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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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 className="app"> <h4>Radio Buttons in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <div className='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..!! 🙂