'setting defaultChecked in radio button is not working in react
I need to set the defaultChecked on page load which can later be changed by the user
<input
ref={(element) => (this['input' + item.key] = element)}
name={item.key}
placeholder='Config value'
defaultChecked={item.value === true}
value='true'
type='radio'
onChange={(event) => this.validateCValue(event.target.value, item)}
/>
<label> True</label>
Solution 1:[1]
Radio inputs can only be checked but not unchecked, if you set it to true, the user will not be able to uncheck it, maybe you meant to use a checkbox?
const [checked, setChecked] = useState(true);
const handleChange = () => {
setChecked(checked => !checked);
};
return (
<div className="App">
<input
placeholder="Config value"
defaultChecked={checked}
type="checkbox"
onChange={handleChange}
/>
<label>{checked ? "checked" : "not checked"}</label>
</div>
);
Solution 2:[2]
this works for me use "checked" tp set radio button default value
<div onChange={this.sethandleValueChange.bind(this)} className={` ${(this.state.IsControlSet && this.state.RadioBtnVal=="" ? styles.control_border_red : "")}`}>
<input type="radio" value="Yes" name="RadioBtnVal" checked={this.state.RadioBtnVal=="Yes"} disabled={(this.state.FormName!="View") ? false : true}/> Yes<br/>
<input type="radio" value="No" name="RadioBtnVal" checked={this.state.RadioBtnVal==="No"} disabled={(this.state.FormName!="View") ? false : true}/> No
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ludwiguer |
Solution 2 | AYUSH CHAUDHARY |