Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting expected parameter on a function from an eventlistner callback

I am using a functional react component in which I am trying to add events to a couple of elements altogether. However I am not able to pass a trigger element to a function

export default function Header() {
    const background = document.querySelector('.dropdownBackground');
    const nav = document.querySelector('.top');

    useEffect(() => {
        let triggers = document.querySelectorAll('.cool > li');
        console.log(triggers);
        triggers.forEach(trigger => {
            trigger.addEventListener('mouseenter', trigger => handleEnter(trigger));
        });
    });

    function handleEnter(trigger) {
        // not getting proper value or trigger here. 
        // I am getting a MouseEvent object instead of a HTML element
        trigger.classList.add('trigger-active');
    }

    return (
        <nav className='header top w-100 justify-content-center'>
            <ul className='cool'>
                <li>
               {/* some HTML code */}
                </li>
            </ul>
        </nav>
    )
}

ADDENDUM: Updated the code to provide all required details.

Thanks!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change:

triggers.forEach(trigger => {
    trigger.addEventListener('mouseenter', trigger =>
handleEnter(trigger));
});

to:

triggers.forEach(trigger => {
    trigger.addEventListener('mouseenter', event => // can also use () instead of 'event', as you are not using it
handleEnter(trigger));
});

If you use (trigger) as a parameter in your arrow functions, you are naming trigger the MouseEvent, and passing it to the handlers

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading