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

253
Visualizações
How to Remove and Add same event listener in React onClick to not stack them up infinitely?

I'm trying to remove and add the same event listener in onClick React event, so when the target element is clicked, an event listener is added to the parent element. On the next click it should get removed to not stack.

Right now I know that a new function gets created each click, so the reference is different in add and removeEventListener and that's why it doesn't work.

I don't know how to solve it and I will appreciate help.

Right now it works as intended, only that event listener doesn't get removed on next click, and they stack up...

I will add that it can't be changed with state and inline style, as this element is not accessible in jsx, but is an svg element inside a chart from external library.

Thanks!

const barClick = (event) => {
    const target = event.target as SVGRectElement;

    // Function to change back
    const changeBack = () => {
      target.style.fill = cvar('colorPrimary');
      console.log('changed');
    };

    // Remove to not stack
    target.parentElement?.removeEventListener(
      'click',
      changeBack
    );

    // Change color
    target.style.fill = cvar('colorSecondary');

    // Add event so color is back to the same once clicked outside
    target.parentElement?.addEventListener(
      'click',
      changeBack
    );
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Based on the docs, there's an option called once which can be added to the addEventListener function so that it is automatically removed over invoked

about 4 years ago · Juan Pablo Isaza 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