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>

2 Answers 2

0

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>
  );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks .. defaultChecked={checked} this line helped me understand on what i was doing wrong..now it worked
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"}
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.