-2

I am trying to add an 'onclick' event to a checkbox like so

<input type='checkbox' name="doneTask" value='done' onClick={removeTask(this)}/>

'removeTask' is defined in the same file

 function removeTask(elem){
    
     //use elem

 }

I want to pass 'this' as argument but the problem is the event gets fired before the click (probably ) because 'removeTask(this)' is seen as a function call. It works fine when I use

onclick = {removeTask}

But I cannot pass 'this' using this method, is there a way to work around this problem?

  • Isn't the callback supposed to provide you with the "event" object that contains the event target? – Salman A Jan 08 '23 at 11:20
  • Your code is **calling** `removeTask` and then setting `onClick` to its return value, see the linked question for details. Separately, `this` is not set by React when calling event handlers. If you want to access the element that the handler is attached to, use the `currentTarget` property of the event object the function receives. – T.J. Crowder Jan 08 '23 at 11:32

3 Answers3

-1

Yes, try passing in a callback function if you wanna pass props: Currently you are only passing the event of the property.

onclick = {() => removeTask(prop1, prop2)}
kazmi066
  • 573
  • 5
  • 15
-1

Pass it in a call-back function

   onClick={()=>function(this)}
MALIK forz
  • 66
  • 6
-1

If you want to call the function on the click event, you just need to call the function with arguments inside another function like this:

<input type='checkbox' name="doneTask" value='done' onClick={()=>removeTask(this)}/>