0

I was learning about React in Codecademy when I came across this example:

class MyClass extends React.Component {
   myFunc() {
     alert('Stop it.  Stop hovering.');
   }

   render() {
      return (
         <div onHover={this.myFunc}>
         </div>
   );
 }

I noticed that when myFunc is called, no parentheses were used and was wondering why. I would appreciate it if someone could explain it.

  • 5
    You are passing the callback name for `onHover` event. Parentheses is needed only if you want to execute the function. – norbitrial May 02 '20 at 18:56
  • 1
    because you are passing the reference to the function... (the function definition so that react can execute it on the event occurance) – anees May 02 '20 at 18:57
  • So: the function/method _isn’t_ called _then_ when parenthesis are not used; in particular, callbacks are usually invoked _later_, in which case parenthesis are used (internally, by react in this case) when it’s actually time to call the function.. – user2864740 May 02 '20 at 18:59
  • This is a behavior of Javascript: Passing function as a parameter. – Menai Ala Eddine - Aladdin May 02 '20 at 19:04
  • This post has clearly explained. https://stackoverflow.com/questions/42178136/when-to-call-function-vs-function-in-react-onclick – Prashanth M May 02 '20 at 19:42

2 Answers2

2

You are only passing the reference to the function if you add () the function will execute every time your webpage is render

0

There are various event present on HTML elements like click, mouse hover etc. if you want to perform some action on hover on HTML element, then browser provide us these methods which will invoked when these action happens.

  • In above case on element hover browser will trigger/call myFunc method(onHover) handler
  • There is no need to call myFunc as it trigger on Hover event
  • OnHover handler should not be called inside render, otherwise it will be invoked every render which is incorrect
Jagannath
  • 1
  • 1