Sometimes, we want to uncheck radio buttons in React.
In this article, we’ll look at how to uncheck radio buttons in React.
How to uncheck radio buttons in React?
To uncheck radio buttons in React, we can set the checked
prop of the radio button to false
.
For instance, we write:
import React, { useState } from "react";
export default function App() {
const [checked, setChecked] = useState({ apple: true, orange: false });
const changeRadio = (e) => {
setChecked(() => {
return {
apple: false,
orange: false,
[e.target.value]: true
};
});
};
return (
<>
<button
onClick={() => setChecked(() => ({ apple: false, orange: false }))}
>
uncheck
</button>
<label>
<input
type="radio"
checked={checked.apple}
value="apple"
name="choice"
onChange={changeRadio}
/>
apple
</label>
<label>
<input
type="radio"
checked={checked.orange}
value="orange"
name="choice"
onChange={changeRadio}
/>
orange
</label>
</>
);
}
We have the checked
state that we use to set the checked
prop of each radio button.
Then we set onChange
to the changeRadio
function.
In changeRadio
, we call setChecked
with a function that sets apple
and orange
both to false
.
Then we set the radio button that we clicked on to be checked by adding [e.target.value]: true
.
We also add a button that calls setChecked
with a function that returns { apple: false, orange: false }
to uncheck both checkboxes.
Finally, we set the checked
prop of each radio button to the property of the checked
state to update the checked value.
Now when we click the uncheck button, both radio buttons should be unchecked.
Conclusion
To uncheck radio buttons in React, we can set the checked
prop of the radio button to false
.