Home > database >  Not getting expected parameter on a function from an eventlistner callback
Not getting expected parameter on a function from an eventlistner callback

Time:04-08

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!!

CodePudding user response:

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

  • Related