score:9

Accepted answer

you're executing the function instead of just setting it, here:

onclick={this.dlthandler(index)}

if you want to pass some arguments bind them. like:

onclick={this.dlthandler.bind(this, index)}

or use an arrow function:

onclick={() => this.dlthandler(index)}

if you notice, we're setting a function while declaring it to onclick. and this function is just executing dlthandler.

score:2

when you define the onclick like this it is calling that function on instantiation. you need to use bind or define an anonymous function:

   <button onclick={this.dlthandler.bind(this, index)}>delete</button>

or

   <button onclick={() => this.dlthandler(index)}>delete</button>

both of these pass a function to the onclick handler - but they do not execute until onclick is fired. note that doing this will cause a new function to be generated on every render call. this can be expensive computationally if you are rendering very often.

if performance becomes an issue it is a better solution to refactor the button into a separate component that has a defined dlthandler function.


Related Query

More Query from same tag