I don't understand checkboxes in ReactJS. I found this question but it has a ton of upvoted answers where everyone is doing something else. Some answers use checked={isCheckedState}
, which however for me throws uncontrolled input error. Other use defaultChecked
, which removes the uncontrolled error but then the checkbox won't change. Some have no value
attribute but when I don't have that, the e.target.value
always returns the string "on".
Can someone please explain to me how checkboxes REALLY should be handled in ReactJS?
const [checkBox, setCheckbox] = useState(false); //default unchecked
const handleCheckbox = (val) => {
setCheckbox(!val); //toggle
console.log(val, checkBox);
}
render(
<input
id="check"
type="checkbox"
value={checkBox} //if I remove this, "val" always contains "on"
defaultChecked={checkBox}
onChange={e => handleCheckbox(e.target.value)}
/>
);