In the FCC course Front End Library → React → Create Controlled Input
When I write the method handleChange(), I pass an arrow function to this.setState but it cannot render correctly.
I’d like to understand the logic behind, and I need some help to get my head straight.
Do you know what’s happening behind?
In the code below, inside handleChange() method
- if using arrow function in this.setState(), the browser console returns error message: type error: cannot read properties of null (reading ‘value’)
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
// Change code below this line
this.handleChange = this.handleChange.bind(this)
// Change code above this line
}
// Change code below this line
handleChange(event) {
this.setState(
state => ({
input: event.target.value
})
// Delete "state =>" above then the whole code works
// if leave the arrow function in it , it shows type error: cannot read properties of null (reading 'value')
)
}
// Change code above this line
render() {
return (
<div>
{ /* Change code below this line */}
<input value={this.state.input} onChange={this.handleChange} />
{ /* Change code above this line */}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};