I am working on a site. The site has two languages. English and arabic. It also has footer and the footer is turned into clickable tabs when it comes to smaller screens. The click functionality works as expected on one version of language. For example, it works good on english version. When i switch to arabic version, the site reloads and the tab onClick event seems to be triggered twice. It seems that the eventHandler is being registered twice when I switch the language.
How can I prevent eventListener from being registered twice?
Below is the code.
import { shape, string } from 'prop-types';
import React, { useEffect, useRef } from 'react';
import { useWindowSize } from '@magento/peregrine/lib/hooks/useWindowSize';
import { useStyle } from '@magento/venia-ui/lib/classify';
import CmsBlock from '@magento/venia-ui/lib/components/CmsBlock';
import defaultClasses from './footer.module.css';
const Footer = ({ classes }) => {
const isMobile = useWindowSize().innerWidth < 1024;
const initialized = useRef(false);
useEffect(() => {
if (!initialized.current && isMobile) {
setTimeout(() => {
initialized.current = true;
const buttonElements = document.querySelectorAll('.col-links');
for (let i = 0; i < buttonElements.length; i++) {
if (isMobile) {
buttonElements[i].addEventListener('click', () => {
console.log("clicked") // gets printed twice on language switch
buttonElements[i].classList.toggle('active-tab');
});
}
if (initialized.current && !isMobile) {
buttonElements[i].classList.remove('active-tab');
}
}
}, 500);
}
}, [isMobile]);
const rootClasses = useStyle(classes, defaultClasses);
return (
<footer id="footer" className={rootClasses.root}>
<div className="footerWrapper">
<CmsBlock identifiers="footer" />
</div>
</footer>
);
};
export default Footer;
Footer.propTypes = {
classes: shape({
root: string
})
};