So, let's say I have a class named Search that is a simple input field with a submit button. Here's the code for that.
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={this.handleChange}
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
So, I need to bind the this
keyword to the event handler, handleChange
, inside the constructor of the class so that it has the correct reference to this
inside the handleChange
event handler.
However, if I change the code to the following
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
//this.handleChange = this.handleChange.bind(this);
Line comment above
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={(e) => this.handleChange(e)}
Line change above
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
Now, if I change the code to the above, I no longer need to do that because I am calling this.handleChange from inside of a callback. Why is this the case?
The reason is that you use an arrow function when you create the callback.
You don't need to bind arrow functions to this, because arrow functions "lexically binds the this value".
If you want, you can change your event handler functions into arrow functions, so that you don't need to bind them. You may need to add the babel plugin 'transform-class-properties' to transpile classes with arrow functions.
If you want to change handleChange
into an arrow function, simply change
handleChange(e) {
...
}
to
handleChange = (e) => {
...
}
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