Close on click outside
This commit is contained in:
parent
c060f5a398
commit
d688c45808
|
@ -2,7 +2,7 @@ import React, {
|
||||||
ReactNode,
|
ReactNode,
|
||||||
ComponentType,
|
ComponentType,
|
||||||
useState,
|
useState,
|
||||||
//useRef,
|
useRef,
|
||||||
useEffect,
|
useEffect,
|
||||||
} from "react";
|
} from "react";
|
||||||
import styles from "./OrganizedContent.module.css";
|
import styles from "./OrganizedContent.module.css";
|
||||||
|
@ -105,7 +105,7 @@ export const OrganizedContent = ({
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Burger {...mobileProps} />
|
<Burger {...mobileProps} />
|
||||||
<Menu {...menuProps} />
|
<MenuWrapper {...menuProps} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
@ -218,6 +218,17 @@ const Burger = ({ open, setOpen }: MobileProps) => {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function MenuWrapper(menuProps: MenuProps) {
|
||||||
|
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||||
|
useOutsideAlerter(wrapperRef, menuProps.setOpen);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={wrapperRef}>
|
||||||
|
<Menu {...menuProps} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const Menu = ({ open, childProps }: MenuProps) => {
|
const Menu = ({ open, childProps }: MenuProps) => {
|
||||||
const mobileNav = open
|
const mobileNav = open
|
||||||
? styles.mobileNav
|
? styles.mobileNav
|
||||||
|
@ -228,3 +239,26 @@ const Menu = ({ open, childProps }: MenuProps) => {
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function useOutsideAlerter(
|
||||||
|
ref: React.RefObject<HTMLDivElement>,
|
||||||
|
setOpen: React.Dispatch<React.SetStateAction<boolean>>
|
||||||
|
) {
|
||||||
|
useEffect(() => {
|
||||||
|
/**
|
||||||
|
* Alert if clicked on outside of element
|
||||||
|
*/
|
||||||
|
const handleClickOutside = (event: Event) => {
|
||||||
|
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bind the event listener
|
||||||
|
document.addEventListener("mousedown", handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
// Unbind the event listener on clean up
|
||||||
|
document.removeEventListener("mousedown", handleClickOutside);
|
||||||
|
};
|
||||||
|
}, [ref, setOpen]);
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue