Home > Mobile >  React how to prevent a parent's onclick event from firing when a child is clicked?
React how to prevent a parent's onclick event from firing when a child is clicked?

Time:08-15

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>

CodePudding user response:

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;
}

CodePudding user response:

Check to see if e.target === e.currentTarget.

function Example() {
  
  function handleClick(e) {
    if (e.target === e.currentTarget) {
      console.log('Only container clicked');
    }
  }

  return (
    <div
      className="container"
      onClick={handleClick}
    >
      <button>Click me!</button>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
#react { padding: 0; border: 0; margin: 0;}
.container { border: 5px solid white; padding: 1em; background-color: lightblue; }
div:hover { border: 5px solid cornflowerblue;  }
div:hover, button:hover { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

CodePudding user response:

You can achieve by doing these.

  1. Check for the target element tag when event is triggered.
  2. Assign Id's to the elements and execute your code based on the Id.
  3. Use CSS pointer-events to disable pointer events of that element.
  • Related