Reputation: 45
I'm trying to use closest way of event handling in ES8 standards. In React, what is the difference in:
handleButtonPressSearch(inputValue) {
this.setState({
showAll: true
});
}
versus
handleButtonPressSearch = (inputValue) => {
this.setState({
showAll: true
});
}
Which is the preferred way?
Upvotes: 1
Views: 134
Reputation: 1074088
what is the difference in
Your first example is a method. When a method is called, this
depends on how the method was called (as with traditional functions using the function
keyword). So if you pass a reference to that method to other code as a callback (for instance, an event handler), you need to ensure this
is set to your component instance, not to something else.
Typically when you use methods, in the constructor you bind them to the instance:
this.handleButtonPressSearch = this.handleButtonPressSearch.bind(this);
Your second example is using class fields syntax and an arrow function. Arrow functions don't care what this
you call them with, they ignore it; instead, they use the this
that was in context where they were created. For a class field, that's the instance. Consequently, you don't need that bind
call; this
within that function will always refer to your component instance.
Note that class fields syntax still isn't standard JavaScript, the proposal is at Stage 3, though, and most React projects are set up to let you use class fields via transpilation.
Which is the preferred way?
Neither is preferred, it's a matter of style. Both have access to the instance, and both can use super
if necessary (though in React, inheritance is usually discouraged).
Upvotes: 3