Last updated: Apr 6, 2024
Reading time·2 min
To set the default checked value of a radio button in React:
checked
property on each radio button conditionally.import React, {useState} from 'react'; export default function App() { // 👇️ Initialize state to default checked radio button const [selected, setSelected] = useState('yes'); const handleChange = event => { console.log(event.target.value); setSelected(event.target.value); }; return ( <div> <div> <input type="radio" id="yes" name="choose" value="yes" checked={selected === 'yes'} onChange={handleChange} /> <label htmlFor="yes">Yes</label> <input type="radio" id="no" name="choose" value="no" onChange={handleChange} checked={selected === 'no'} /> <label htmlFor="no">No</label> <input type="radio" id="maybe" name="choose" value="maybe" onChange={handleChange} checked={selected === 'maybe'} /> <label htmlFor="maybe">Maybe</label> </div> </div> ); }
We used the useState hook to track the value of the selected radio button.
const [selected, setSelected] = useState('yes');
input
field has an onChange
prop, so every time the value changes, the handleChange
function runs and we update the state with the value of the clicked radio button.const handleChange = event => { console.log(event.target.value); setSelected(event.target.value); };
This works, because we have initialized the state variable to the value of the radio button we want to check by default.
const [selected, setSelected] = useState('yes');
We passed an initial value of yes
to the useState
hook, so the condition in
the radio button's checked prop will be true
for the input
field with
value
set to yes
.
The checked
prop on each input conditionally checks if the selected
state
variable is equal to the input's value
prop.
<input type="radio" id="yes" name="choose" value="yes" checked={selected === 'yes'} onChange={handleChange} /> <label htmlFor="yes">Yes</label>
If they are equal, the radio button gets checked.
This is how we are able to set the default checked value of a radio button:
checked
prop on each radio button to conditionally check whether
the state variable is equal to its value.name
prop.If you don't assign the same name
prop value to all of the radio input
fields in the group, you will be able to check multiple radio buttons at the
same time.
If this is the behavior your use case requires, you should be using a checkbox instead of a radio button.
I've also written an article on how to set the default checked value of a checkbox.