difference between passing {SomeFunction} and {SomeFunction()} in reactjs event handling

Viewed 72
import React from "react";

const FunctionClick = () => {
  const clickHandler = () => {
  console.log("Button clicked.");
  };

  return (
    <div>
      <button onClick={clickHandler}>Click</button>
    </div>
  );
};

export default FunctionClick;

{REACT NOOBIE ALERT} In the above code, I can see the difference in the output of

<button onClick={clickHandler}>Click</button>

and

<button onClick={clickHandler()}>Click</button>

but can someone explain why we are passing the function and not calling it?

How is the function (in second code) being called when the page loads even though we want to call it when the button is clicked.

3 Answers

Here you are passing the function(object) reference, which will not be called until you call it explicitly, since its in onClick and on click calls the function when click event occurs.

<button onClick={clickHandler}>Click</button>

Here you are passing the return value of the clickHandler, now it depends on you what value/object you return from clickHandler, since onClick in react expects a function reference to be called so you must return a function from clickHandler else it will throw a error.

<button onClick={clickHandler()}>Click</button>

When used with parentheses, that function is called every time the page is rendered But Without parentheses, it is called when clicked

 import React, { Component } from 'react';

class sample extends React.Component {
constructor(props) {
        super(props)


       this.clickHandler=this.clickHandler.bind(this);

}
 clickHandler() {
  console.log("Button clicked.");
  };
 render() {
  return (
    <div>
      <button onClick={this.clickHandler}>Click</button>
    </div>
  );
};
}
export default FunctionClick;

or

    <button onClick={() => this.clickHandler()}>
 Click
      </button>

for your code

import React from "react";


function FunctionClick () {

  function clickHandler () {
   console.log("Button clicked.");
  }
  return (
    <div>
      <button onClick={clickHandler}>Click</button>
    </div>
  );
};

export default FunctionClick;

The mistake in your code is, not giving a function as onClick.

<button onClick={clickHandler()}>Click</button> - This is not correct, here we are executing the clickHandler function.

Instead do this way, (when explicitly want to pass arguments to the function)

<button onClick={(e) => {clickHandler(e)}}>Click</button>
Related