Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make default checked for radio buttons in react?

Tags:

reactjs

How to make the radio button checked if the initial value is true?

like image 394
Tim Avatar asked Jul 13 '17 06:07

Tim


People also ask

How do I keep a radio button checked by default?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

How do you check if a radio button is checked react?

To check/uncheck a radio button in React, we use the checked property of the input elements, which is set to true when the radio button is checked otherwise it is set to false .

Does checked work for radio buttons?

If a radio button is checked, its checked property is true .

How do I select the first radio button as default?

This can be done using ".getElementById. And the output will be shown in a Boolean value. After clicking "Tap to check" button, it will show whether the radio button is by default clicked or not.


2 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" /> 
like image 192
Hugo Silva Avatar answered Sep 25 '22 20:09

Hugo Silva


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/

like image 38
crazycoder65 Avatar answered Sep 26 '22 20:09

crazycoder65