Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda