Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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>
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
}
about 4 years ago · Santiago Trujillo Report

0

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>

about 4 years ago · Santiago Trujillo Report

0

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.
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!