Reputation: 91
I have begun to notice an unusual pattern. Any onClick event requires the syntax to be
onClick={() => «name of function»}
.
I have also spent time researching as to the reason why onClick seems to be the only event handler which requires the paranthesis, but all I can find are articles that explain what to do but not why it works that way. OnChange and other events do not require that same syntax, but they are all types of events. All advice and explanations are welcome.
Upvotes: 1
Views: 775
Reputation: 1091
Usually, when it comes to React components, the functions probably are using the this.setState
method or even accessing to the component props (eg: this.props
), so the methods need to use the right this
keyword (which is dynamically bound).
The arrow functions are great for this purpose, they provide a nice syntax and also a they don't have its own this
, which means that the this
that are used inside them are the same as the parent this
.
So when you need to pass an event handler to a component without changing the meaning of the this
keyword you can do the following:
arrow function
eventHandler = () => console.log(this.props)
...
onClick={this.eventHandler}
arrow function
onClick={() => this.eventHandler()}
Function.prototype.bind
methodonClick={this.eventHandler.bind(this)}
Note: Is important to mention that if you want to pass an eventHandler to onClick
, it should be a reference, otherwise your event handler will be executed everytime the component is rendered.
Upvotes: 2
Reputation: 1876
onClick doesn't require "the parenthesis". That's an arrow function, it's one of several ways of passing an event handler to the component.
This is one way:
onClick={this.nameOfFunction} // In this case, you need to bind the this in the constructor.
This is another way:
onClick={this.nameOfFunction.bind(this)}
And this is another one:
onClick={() => this.nameOfFunction()}
But, as the docs says: "Using an arrow function in render creates a new function each time the component renders, which may have performance implications (see below)."
Upvotes: 4