Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda