Languages
[Edit]
EN

Simple way to use multiple radio buttons in React

3 points
Created by:
Dragontry
731

Many beginners haveĀ a problem with using multiple radio buttonsĀ because they do not realize that the radio buttons are grouped and only oneĀ radio button can be selected in oneĀ group.

Today, I'd like to show you how to easily use multiple radio buttons without using grouping by the input name property in React. 😊

Final effect:

Multiple radio buttons in ReactJS.
Multiple radio buttons in ReactJS.

In below example I've createdĀ RadioInputĀ functional component which rendersĀ labelĀ with a singleĀ input type="radio"Ā (radio button).

In theĀ FormĀ we have four RadioInputĀ elements - two for gender and, two for role.

In every group we can selectĀ only one radio button atĀ the same time, thenĀ setGenderĀ function setsĀ genderĀ 🧒🧑Ā andĀ setRoleĀ function setsĀ roleĀ dependingĀ on which option we choose.Ā 

Runnable example:

// ONLINE-RUNNER:browser;

/// Note: Uncomment import lines in your project.
// import React from 'react';

const RadioInput = ({label, value, checked, setter}) => {
	return (
	  <label>
	    <input type="radio" checked={checked === value} onChange={() => setter(value)} />
	    <span>{label}</span>
	  </label>
	);
};
   
const Form = (props) => {
	const [gender, setGender] = React.useState();
	const [role, setRole] = React.useState();
	const handleSubmit = e => {
		e.preventDefault();
		const data = {gender, role};
		const json = JSON.stringify(data, null, 4);
		console.clear();
		console.log(json);
	};
	return (
	  <form onSubmit={handleSubmit}>
	    <div>
	      <label>Gender:</label>
	      <RadioInput label="Male" value="male" checked={gender} setter={setGender}  />
	      <RadioInput label="Female" value="female" checked={gender} setter={setGender} />
	    </div>
	    <div>
	      <label>Role:</label>
	      <RadioInput label="Admin" value="admin" checked={role} setter={setRole} />
	      <RadioInput label="User" value="user" checked={role} setter={setRole}  />
	    </div>
	    <button type="submit">Submit</button>
	  </form>
	);
};

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );

If you found this solution useful and would like to receive more content like this let me know by leavingĀ a reaction.

Thanks for your time and see you in the upcoming posts! 😊

Ā 

Related posts

  1. React - multiple radio buttons

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS - Blog posts

Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join