Click listener firing multiple times in react

32 Views Asked by At

I am working on a magento 2 PWA studio project and a click listener seems to be firing multiple times. I have two languages in website. On the first one, the click listener fires fine. When i switch to the second language, it fires multiple times. Below is the code.

import CmsBlock from '@magento/venia-ui/lib/components/CmsBlock';

const isMobile = useWindowSize().innerWidth < 1024;
const footer = <CmsBlock identifiers="footer" />;

const handleTabClick = useCallback((element) => {
        console.log('handleTabClick')
        element.classList.contains('active-tab') ? element.classList.remove('active-tab') : element.classList.add('active-tab');
    });

useEffect(() => {        
     const buttonElements = document.querySelectorAll('.col-links');
     if (isMobile) {
         buttonElements.forEach(element => {
              element.addEventListener('click', handleTabClick.bind(null, element));
         })
     } else {
         buttonElements.forEach(element => {
              element.classList.contains('active-tab') && element.classList.remove('active-tab');
            })
        }
}, [isMobile, footer, handleTabClick]);

If i return from useEffect and remove the event listener at component un render time,the click listener does not seem to be fired at all when i switch the language. What is wrong with my code?

Note: When language switch happens, the entire website is refreshed.

0

There are 0 best solutions below