From e256be2fba48b0577daa1bdc3d21530b6c8da945 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Tue, 27 Dec 2022 17:09:45 -0800 Subject: [PATCH] Clicking outside the menu hides it The method in Header got committed two commits ago (oops) but this makes it so a click or tap outside an opened menu hides it --- components/HeaderMenu/index.tsx | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/components/HeaderMenu/index.tsx b/components/HeaderMenu/index.tsx index d5eee157..354e897a 100644 --- a/components/HeaderMenu/index.tsx +++ b/components/HeaderMenu/index.tsx @@ -20,6 +20,7 @@ interface Props { authenticated: boolean open: boolean username?: string + onClickOutside: () => void logout?: () => void } @@ -31,6 +32,8 @@ const HeaderMenu = (props: Props) => { const accountData: AccountCookie = accountCookie ? JSON.parse(accountCookie as string) : null + // Refs + const ref: React.RefObject = React.createRef() const userCookie = getCookie('user') const userData: UserCookie = userCookie @@ -38,6 +41,22 @@ const HeaderMenu = (props: Props) => { : null const localeCookie = getCookie('NEXT_LOCALE') + useEffect(() => { + const handleClickOutside = (event: Event) => { + if ( + ref.current && + event.target instanceof Element && + !ref.current.contains(event.target) && + props.open + ) { + props.onClickOutside() + } + } + document.addEventListener('click', handleClickOutside, true) + return () => { + document.removeEventListener('click', handleClickOutside, true) + } + }, [props.onClickOutside]) const [checked, setChecked] = useState(false)