简体   繁体   中英

How to close a menu in react when clicked outside the menu but on the menu button

So i have a NavbarItem that toggles a menu.

<NavbarItem
   icon={<CaretDownFill />}
   onPress={() => setOpenMenu(!openMenu)}
>

Using this useEffect i determine if a click was outside the menu so it closes.

    const dropdownMenu = useRef();
    useEffect(() => {
      let handleClick = (event) => {
         if (!dropdownMenu.current?.contains(event.target)) {
            setOpenMenu(false);
         }
      }
      document.addEventListener("mousedown", handleClick)
      return () => { document.removeEventListener("mousedown", handleClick) }
   });

Now the problem is that whenever i click the NavbarItem the above useEffect triggers and the menu closes but it opens again because the click was on the NavbarItem that opens the menu.

I have tried adding a ref on the NavbarItem it self and checking if the click was outside the menu AND the NavbarItem and it works but it feels wrong.

Is there any way to solve this without adding a ref to the NavbarItem?

You could disable the onPress function while the menu is open.

<NavbarItem
   icon={<CaretDownFill />}
   onPress={openMenu ? undefined : () => setOpenMenu(true)}
>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM