Set the default checked value of a Radio button in React

avatar

Borislav Hadzhiev

Thu Apr 21 20222 min read

Set the default checked value of a Radio button in React #

To set the default checked value of a radio button in React:

  1. Store the radio button value in the state.
  2. Initialize the state to the value of the default checked radio button.
  3. Set the checked property on each radio button conditionally, e.g. checked={selected === 'yes'}.
App.js
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.

Each 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.

This works, because we have initialized the state variable to the value of the radio button we want to check by default.

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.

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:

  1. We initialize the state variable to the value of the specific radio button.
  2. We set the checked prop on each radio button to conditionally check whether the state variable is equal to its value.
Note that checking a radio button, automatically unchecks all other radio buttons with the same 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.