Skip to content Skip to sidebar Skip to footer

Onclick Event Fired Before Clicking In React

I want to remove the li whenever user click the delete button. So I pass the index around but it got triggered before I click on it, I guess I'm doing it wrong for passing the valu

Solution 1:

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.

Solution 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

<buttononClick={() => 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.

Post a Comment for "Onclick Event Fired Before Clicking In React"