I receive this error
Error:(17, 35) TS2339: Property 'checked' does not exist on type 'EventTarget & Element'.
But that's definitely impossible error because React docs says checked
does exist on target
of checkbox (https://reactjs.org/docs/forms.html#handling-multiple-inputs)
Here is my code. What's wrong with it so TS blows up?
// I specify a type for event. It must have `checked` property.
onToggle = (ev: React.ChangeEvent) => {
console.log('[ev]', ev.target.checked); // <= TS throws here
}
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
</div>
)
}
Alternative error message:
TS2339: Property 'checked' does not exist on type 'EventTarget'.
Here is a fix. You have to specify type of the element of ChangeEvent
onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
// onToggle = (ev: React.ChangeEvent) => {
console.log('[ev]', ev.target.checked); // <= TS throws here
}
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
</div>
)
}
Check out this, I currently apply this way to my project.
onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
console.log('[ev]', (ev.target as HTMLInputElement).checked);
}
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={onToggle} checked={this.state.on}/>
</div>
)
}
Btw, I think you should try useState
for getting/setting the state of the checked
value. For example:
const [checked, setChecked] = useState(false)
const onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
setChecked((ev.target as HTMLInputElement).checked);
};
...
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={onToggle} checked={checked}/>
</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With