How to make the radio button checked if the initial value is true?
5 Answers
Using the defaultChecked property, available for <input type="checkbox"> and <input type="radio"> - https://reactjs.org/docs/uncontrolled-components.html#default-values
<input type="radio" name="radio-group" value="1" defaultChecked />
<input type="radio" name="radio-group" value="2" />
<input type="radio" name="radio-group" value="3" />
5 Comments
checked takes precedence over defaultChecked. You shouldn't use both at the same time. This approach is intended for uncontrolled components only - reactjs.org/docs/uncontrolled-components.html{[1, 2, 3].map((num) => (<input type="radio" name="group1" value={num} />))} Adding defaultChecked sets the last radio button created as the checked value, where I was wanting to have the first value set.defaultChecked in the example above, is a shorthand for the value true. So, to use the attribute conditionally, you can assign a boolean value to it. In your case defaultChecked={num === 1}.Sometimes the issue can be fixed by removing the name attribute and instead using a conditional checked value:
<li>
<label>
<input
type="radio"
value="medium"
checked={this.state.size === "medium"}
onChange={this.handleChange}
/>
Medium
</label>
</li>
<li>
<label>
<input
type="radio"
value="large"
checked={this.state.size === "large"}
onChange={this.handleChange}
/>
Large
</label>
</li>
Source Here: https://magnusbenoni.com/radio-buttons-react/
Comments
I found an answer to my question under @Hugo Silva's top answer.
I was looking to set the default to "1" out of a list of 5, and I generated the list of each with a map() call to reduce written code. This led to the last element being selected for the defaultChecked value, which I didn't want.
My solution is as follows:
{[1, 2, 3, 4, 5].map((num) => (
<input
defaultChecked={num === 1} // returns bool, only true for first input
type="radio"
name="group1"
value={num}
/>
))}
defaultCheckedprop