React JS: calling event handlers Code Answer

I have started working in React recently. I noticed one behaviour like when I am trying to call my event handle with the same component like this onClick={someEventHandler} it is triggering but when I try to do the same same like this onClick={()=> someEventHandler} it doesn’t work.

I noticed that when I need to pass any arguments and calling the function like onClick={()=>someEventHandler(id)} it is working fine.

can some one explain me the logic/theory behind this?

Answer

The onClick event handler needs a function to be passed to it. Whenn the event is triggered, it calls the handler function passed to it.

In the first case it works because you pass someEventHandler to onClick which is invoked when event is fired. An invocation to the function is like someEventHandler()

Now in the second case,

onClick={()=>someEventHandler}

the function passed to onClick is ()=>someEventHandler which can be elaborated further as ()=> { return someEventHandler; }

Now if you notice above you are returning a function from the onClick event handler. The returned function is now never invoked and hence you see the above behavior

It works in the last case like onClick={()=>someEventHandler(id)}, because when the event handler is invoked, it invoked someEventHandler with id too.

However you do not need to pass id to invoke it, you can simply use it like onClick={()=>someEventHandler()} and it work, provided you don’t need id as a parameter in someEventHandler.

Another thing to note when you are using function like onClick={()=>someEventHandler()} instead of onClick={someEventHandler} is that your someEventHandler will not be invoked with any arguments. If you want the event to be passed as argument to someEventHandler, you need tto explicitly pass it like

onClick={(e)=>someEventHandler(e)}

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji