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

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

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