Home > database >  passing event handler as reference
passing event handler as reference

Time:10-29

this is an exercise from codecademy. Why does it require to pass the event handler as a reference? why i can't type onClick={goBack()} instead of onClick={goBack}

const goBack = () => {
    setQuestionIndex(prevQuestionIndex => prevQuestionIndex - 1);
  }

....

 <button onClick={goBack}>
          Go Back
 </button>

CodePudding user response:

goBack is a reference to a function, goBack() calls that function and returns the result.

In the case of the click handler for a button, of course, you want the function to run when the button is clicked, not when the button is rendered. That's why you need to pass the function, rather than calling it (on render) and passing its result.

CodePudding user response:

If you pass in the function call instead of the reference, it will call the function as soon as your component renders, the reference is bound to the click handler, hence when the specific event triggers, it will callout to the reference.

Here is a snippet to see this, Codesandbox Demo

But If you are using as onClick={goBack}, then In this case you are passing a reference to the onClick which means when user click on the button then It will automatically invoke the function. You don't have to invoke the function yourself.


1) Let say consider function with value

<button onClick={fun()}> button with function reference</button>

If you are passing value to a function then first of all it will produces a warning in the console as:

Warning:
Expected `onClick` listener to be a function, instead got a value of `string` type.

and when you invoke it then it will throw error as

Error
Expected `onClick` listener to be a function, instead got a value of `string` type.

2) If you are using as

<button onClick={fun}> button with function reference</button>

then function fun will be passed as a prop and when use click on the function then this function fun will get invoked automatically

  • Related