0

I've use this method : Detect click outside React component

The problem is :

I have a component for a burger menu that as a state. State determine if menu should be open or not. The 2 components are not in the same container. When I click burger, I just toggle state (!state). When I click outside the menu I say state = false But when I click the burger it now says (!state AND state = false) which cause the menu to stay open when clicking again to (try to) close it.

Burger icon code :

const onClick = () => {
    setDeployMode(!deployMode);
    dispatch(deployModeAsideMenu({ deployMode: !deployMode }));
  };

<HamburgerButton
            open={asideMenu.deployMode}
            width={28.88}
            height={25.27 / 1.5}
            strokeWidth={3}
            color={asideMenu.deployMode ? "var(--black)" : "var(--pink)"}
            animationDuration={0.5}
            onClick={onClick}
          />

Aside menu as a ref wrapper :

  const [deployMode, setDeployMode] = useState(false);
  const changeDeployMode = () => {
    setDeployMode(!deployMode);
    dispatch(deployModeAsideMenu({ deployMode: !deployMode }));
  };
  useEffect(() => {
    setDeployMode(asideMenu.deployMode);
    setLandscapeMode(asideMenu.landscapeMode);
  }, [asideMenu]);

  const useOutsideAlerter = ref => {
    useEffect(() => {
      const handleClickOutside = event => {
        if (ref.current && !ref.current.contains(event.target) && window.innerWidth < 900) {
          setDeployMode(false);
          dispatch(deployModeAsideMenu({ deployMode: false }));
        }
      };
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, [ref]);
  };
 const wrapperRef = useRef(null);
 useOutsideAlerter(wrapperRef);


// asideMenu comp

<AsideMenuContainer
      ref={wrapperRef}>

// as other code here
<AsideMenuContainer />
Alexis K
  • 13
  • 5

0 Answers0