PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] Why to pass function reference instead of method in onClick event of button in ReactJS?

 July 05, 2022     event-handling, pass-by-reference, reactjs     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing