DEV Community

Cover image for Simple way to use multiple radio buttons in React

Posted on • Originally published at

Simple way to use multiple radio buttons in React

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 groups (without using the name parameter) in React. 😊

Before we start, I would highly recommend you to check out runnable example for the solution on our website:
Simple way to use multiple radio buttons in React

Final effect:image

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.

Practical example:

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';

const RadioInput = ({label, value, checked, setter}) => {
    return (
        <input type="radio" checked={checked == value}
               onChange={() => setter(value)} />

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

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

You can run this example here

If you found this solution useful and would like to receive more content like this leave a comment or reaction 💗🦄💾.
Thanks for your time and see you in the upcoming posts! 😊🔜

Write to us! ✉

If you have any problem to solve or questions that no one can answer related to a React or JavaScript topic, or you're looking for a mentoring write to us on -> Questions

You can also join our facebook group where we share coding tips and tricks with others! 🔥

Top comments (1)

lionelrowe profile image

Why would you want to deliberately render un-semantic HTML when a semantic option (name) already exists?