Issue
Whenever I pass function parentheses in onClick of button, it automatically calls when page loads even without clicking on button. But when I don't pass function parentheses in onClick of button, it calls only when button is clicked.
With passing parentheses in function call
<button onClick={this.handleButtonClick()}>Increment</button>
Without passing parentheses in function call
<button onClick={this.handleButtonClick}>Increment</button>
Why function called automatically on page load whenever I pass parentheses to function even-though it is written inside onClick of button ?
Solution
There's a difference between a function call and a function.
When a component renders, all statements are executed and expressions are evaluated. It's plain javascript, that's how javascript works.
this.handleButtonClick()
is a function call, and therefore the function will be called once the component renders. I assume that handleButtonClick()
returns undefined
which will cause the button to render as <Button onClick={undefined} />
. Now, if onClick
is undefined
, nothing will happen when the click actually happens as there is no function to be called.
this.handleButtonClick
is just a reference to a function, it doesn't invoke it. You need to pass the function reference to onClick
prop so that it can be called later by React, once the click actually happens.
Answered By - Ante Gulin Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.