'How can I add or remove class using react functional component

I am using react typescript. I am trying to add or remove an active class if I click any list item but the code is sometimes not working. So I want to update my code in a better way. can anyone help me to improve update my below function code?

Here is my function which I want to update

   const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(e: any) {
        list.forEach((item) => item.classList.remove('active'))
        e.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', (e) => activeLink(item)))

Full code with HTML



export default function MobileNavigation() {
    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))



    return <div className='mobile-navigation'>
        <ul>
            <li className='m-list active'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-house"></i></span>
                    <span className='m-text'>Home</span>
                </a>
            </li>
            <li className='m-list'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-shop"></i></span>
                    <span className='m-text'>Shop</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-store"></i></span>
                    <span className='m-text'>Vendors</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-address-card"></i></span>
                    <span className='m-text'>About us</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-headset"></i></span>
                    <span className='m-text'>Contact Us</span></a>
            </li>
            <div className="indicator"></div>
        </ul>
    </div>;
}



Solution 1:[1]

Your code is pure VanillaJS, not Typescript or React. Try to read something about Typescript AND React, make example project and try - https://medium.com/codex/typescript-and-create-react-app-11bdebcbf763

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zbyso