Home > other >  why I need to pass a function in return statement in handler of onChange event
why I need to pass a function in return statement in handler of onChange event

Time:10-10

enter image description here Problem in onchange event Handler. You can see output of this code in second photo. Already 8 time event fired without change any checkbox. enter image description here Out Put of this code is hereenter image description here When I Used return Function in handler and click on any check box its worked expectedly ?????

enter image description here You can see only one time event fired . what is the reason behind it ???

CodePudding user response:

To work properly you need to use below input tag

<input onChange={()=>handler()} type="checkbox">

or

<input onChange={handler} type="checkbox">

If you use onChange={handler()} then you are calling the handler method at every render.

CodePudding user response:

Just pass onChange={handler} and not onChange={handler()}. This applies to other similar functions as well like <button onClick={handleClick} />.

Since here you're using onChange, and you will require event for onChange, here's what your need to do

<input onChange={(event)=>handler(event)} />

const handler = (event) => { ...//use the event here }

  • Related