2

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>
ludwiguer
  • 2,177
  • 2
  • 15
  • 21
Asha Aradhya
  • 23
  • 1
  • 5

2 Answers2

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>
  );
ludwiguer
  • 2,177
  • 2
  • 15
  • 21
  • Thanks .. defaultChecked={checked} this line helped me understand on what i was doing wrong..now it worked – Asha Aradhya Jun 24 '20 at 20:02
  • Yeah, that's weird. I encountered a similar problem, after hours of trial and error, I simply had to change my code from `defaultChecked={value === 'string'}` to `defaultChecked={value === 'string' ? "true" : "false"}` – Siklab.ph Nov 17 '20 at 14:44
0

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>