Home > Blockchain >  mouseleave event not firing in gatsby component
mouseleave event not firing in gatsby component

Time:12-08

I'm trying to create a drop down menu component and the mouseleave is not firing on the div. If i use document.addEventListerner('click', handleEvent) it fires just fine and works as expected but i need it to fire on mouseleave. The component is below.

const MenuDropDown: React.FC<Props> = ({ menuLinks, setFocus, focus, explore }) => {
const ref = useRef<HTMLDivElement>(null);

useEffect(() => {
    /**
     * Alert if hovered outside of element
     */
    function handleUserEvent(event: any) {
        console.log(ref.current);
        if (ref && ref.current) {
            setFocus(false);
        }
    }
    // Bind the event listener

    ref.current?.addEventListener('mouseleave', handleUserEvent);
    return () => {
        ref.current?.removeEventListener('mouseleave', handleUserEvent);
    };
}, [ref]);

return (
    <S.Wrapper explore={explore}>
        <S.Container id="container" ref={ref}>
            {menuLinks.length > 0 &&
                menuLinks.map((data, key) => {
                    const url = data.url;
                    const title = data.title;
                    return (
                        <S.StyledLink key={key} activeStyle={{ background: 'rgb(245, 245, 244)' }} to={url}>
                            {title}
                        </S.StyledLink>
                    );
                })}
        </S.Container>
    </S.Wrapper>
);

};

export default MenuDropDown;

CodePudding user response:

I've tested your code in this way and was working fine:

import { useEffect, useRef, useState } from 'react';

const MenuDropDown = ({ menuLinks = [{ title: 'test' }], explore }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [focus, setFocus] = useState<boolean>(false);

  useEffect(() => {
    /**
     * Alert if hovered outside of element
     */
    function handleUserEvent(event: any) {
      console.log('target: ', ref.current);
      if (ref && ref.current) setFocus(false);
    }
    // Bind the event listener

    ref.current?.addEventListener('mouseleave', handleUserEvent);
    return () => {
      ref.current?.removeEventListener('mouseleave', handleUserEvent);
    };
  }, [ref]);

  return (
    <div explore={explore}>
      <div id="container" ref={ref}>
        {menuLinks?.length > 0 &&
          menuLinks.map((data, key) => {
            const url = data.url;
            const title = data.title;
            return (
              <div key={key} activeStyle={{ background: 'rgb(245, 245, 244)' }} to={url}>
                {title}
              </div>
            );
          })}
      </div>
    </div>
  );
};

export default MenuDropDown;

enter image description here

  • Related