How to handle and manage radio buttons state in React

#react

Last updated on Aug 7, 2021 by Suraj Sharma



In this tutorial, you will learn how you can handle and manage the state of radio buttons in React without using any 3rd party form libraries.

Consider you have a <Form /> component, which contains few Radio buttons and you want to manage and store their state when you click on the radio buttons.


import React from 'react';

const Form = () => {
  const [gender, setGender] = React.useState('male');

  return (
    <form>
      <p>Gender</p>
      <div>
        <input type="radio" /> Male
      </div>
      <div>
        <input type="radio" /> Female
      </div>
      <div>
        <input type="radio" /> Transgender
      </div>
    </form>
  )
}


We have defined a local state gender and a setter function setGender, which is associated with the gender radio buttons.

To check/uncheck a radio button in React, we use the checked property of the input elements, which is set to true when the radio button is checked otherwise it is set to false.


import React from 'react';

const Form = () => {
  const [gender, setGender] = React.useState('male');

  const handleChange = (event) => {
    setGender(event.target.value)
  }
  return (
    <form>
      <p>Gender</p>
      <div>
        <input
          type="radio"
          value="male"
          checked={gender === 'male'}
          onChange={handleChange}
        /> Male
      </div>
      <div>
        <input
          type="radio"
          value="female"
          checked={gender === 'female'}
          onChange={handleChange}
        /> Female
      </div>
      <div>
        <input
          type="radio"
          value="transgender"
          checked={gender === 'transgender'}
          onChange={handleChange}
        /> Transgender
      </div>
    </form>
  )
}


To change the radio buttons local state, we use onChange event handler handleChange to call setGender setter function to manage current radio button state.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.