Skip to content
Advertisement

React how to prevent a parent’s onclick event from firing when a child is clicked?

I have set the onClick prop on my div which will navigate to a new page when clicked. svg is absolutely positioned. How do I avoid the click event on the svg element?

I’ve already tried stopPropagation() but it doesn’t work.

<div
  className={classes.container}
  onClick={() => navigate(`${props.productName}`)}
>
  <img src={props.image} alt="" />
  <svg></svg>
</div>

Advertisement

Answer

Well the obvious answer would be to put it outside of the div.
But if you really can’t, you can always use CSS for this.

Try using pointer-events

Example:

HTML –

<div
  className={classes.container}
  onClick={() => navigate(`${props.productName}`)}
>
  <img src={props.image} alt="" />
  <svg className='no-events'></svg>
</div>

CSS –

.no-events {
   pointer-events: none;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement