I've been working with React TypeScript, and I'm encountering some issues with adding or removing an active class when clicking on list items. The code seems to be unreliable at times, so I'm looking to enhance it for better functionality. Can anyone assist me in improving the following function code?
Below is the function that requires updating:
const menuItems = document.querySelectorAll('.m-list') as NodeListOf<Element>
function handleActiveLink(e: any) {
menuItems.forEach((item) => item.classList.remove('active'))
e.classList.add('active')
}
menuItems.forEach(item => item.addEventListener('click', (e) => handleActiveLink(item)))
Full Code with HTML:
export default function MobileNavigation() {
const menuItems = document.querySelectorAll('.m-list') as NodeListOf<Element>
function handleActiveLink(this: any) {
menuItems.forEach((item) => item.classList.remove('active'))
this.classList.add('active')
}
menuItems.forEach(item => item.addEventListener('click', handleActiveLink))
return <div className='mobile-navigation'>
<ul>
...
</ul>
</div>;
}