Home > Software engineering >  How to Remove and Add same event listener in React onClick to not stack them up infinitely?
How to Remove and Add same event listener in React onClick to not stack them up infinitely?

Time:11-15

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
    );
  };

CodePudding user response:

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

  • Related