Home > Mobile >  Make the children element of a parent that has onClick immune
Make the children element of a parent that has onClick immune

Time:07-19

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>

CodePudding user response:

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 */}}>
  • Related