nevoni3008
nevoni3008

Reputation: 447

Make the children element of a parent that has onClick immune

So I have a product wrapper that I want to be clicked and on click redirect the user to the specific page of that product. And inside that is the button that can add the product to the cart, but the problem occurs here, because the wrapper has onCLick, when I click the button, the parent onClick is called, So I don't know how to make the button immune to the onCLick of the div.

<div onClick={() => navigate(product.id)}>
  <button onClick={() => add(product.id)>Add to Cart</button>
</div>

Upvotes: 2

Views: 1212

Answers (1)

Aymendps
Aymendps

Reputation: 1530

When the onClick event of a child is called, the event propagates by default and calls the onClick of the parent.

To avoid that, you should call event.stopPropagation() inside the child function.

<button onClick={(event)=>{event.stopPropagation(); /* rest of your code */}}>

Upvotes: 2

Related Questions