How to make the radio button checked if the initial value is true?
Asked
Active
Viewed 7.5k times
45
-
Possible duplicate of [How to set default Checked in checkbox REACT js](https://stackoverflow.com/questions/32174317/how-to-set-default-checked-in-checkbox-react-js) – ivarni Jul 20 '17 at 07:16
-
1It sounds like you're looking for the `defaultChecked` prop – ivarni Jul 20 '17 at 07:17
5 Answers
77
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" />

Hugo Silva
- 6,748
- 3
- 25
- 42
-
could you tell me how do I get the value of first input that is defaultChecked with using any onClick or onChange listeners ? – Chandler Bing Sep 08 '21 at 07:52
-
-
@UMR `checked` takes precedence over `defaultChecked`. You shouldn't use both at the same time. This approach is intended for uncontrolled components only - https://reactjs.org/docs/uncontrolled-components.html – Hugo Silva Apr 28 '22 at 00:30
-
How would one use this when generating multiple radio buttons via map()? e.g. `{[1, 2, 3].map((num) => ())}` Adding `defaultChecked` sets the last radio button created as the checked value, where I was wanting to have the first value set. – Swirle13 Jun 28 '23 at 00:59
-
@Swirle13 an attribute without a value, such as `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}`. – Hugo Silva Jun 29 '23 at 02:16
11
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/

justdrinkcoffee
- 53
- 2

crazycoder65
- 341
- 3
- 7
0
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}
/>
))}

Swirle13
- 71
- 6