Last updated on Oct 1, 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 have used onChange
event handler handleChange
to call setGender
setter function to manage current radio button state.
To reset radio buttons in React on click of a Reset button, we set empty string ''
or null
value to the radio state gender
on click of the button.
Pass the resetRadioState
function to the onClick
event handler.
const Form = () => {
const [gender, setGender] = React.useState('male');
const handleChange = (event) => {
setGender(event.target.value)
}
const resetRadioState = () => {
setGender('');
}
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>
<div>
<button
type="reset"
onClick={resetRadioState}
/>
</div>
</form>
)
}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.