From 9eb5d1edcf7f3b0e525e90b98afe416c4be35be0 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Tue, 1 Feb 2022 23:51:33 +0100
Subject: chore: close mainNav on click outside or route change

---
 src/components/MainNav/MainNav.tsx | 27 +++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)

(limited to 'src/components/MainNav/MainNav.tsx')

diff --git a/src/components/MainNav/MainNav.tsx b/src/components/MainNav/MainNav.tsx
index a866b9c..e996e89 100644
--- a/src/components/MainNav/MainNav.tsx
+++ b/src/components/MainNav/MainNav.tsx
@@ -9,7 +9,7 @@ import {
 import { NavItem } from '@ts/types/nav';
 import Link from 'next/link';
 import { useRouter } from 'next/router';
-import { SetStateAction } from 'react';
+import { SetStateAction, useCallback, useEffect, useRef } from 'react';
 import { useIntl } from 'react-intl';
 import styles from './MainNav.module.scss';
 
@@ -22,6 +22,29 @@ const MainNav = ({
 }) => {
   const intl = useIntl();
   const router = useRouter();
+  const mainNavRef = useRef<HTMLDivElement>(null);
+
+  const handleVisibility = useCallback(
+    (e: MouseEvent | FocusEvent) => {
+      if (
+        mainNavRef.current &&
+        !mainNavRef.current.contains(e.target as Node)
+      ) {
+        setIsOpened(false);
+      }
+    },
+    [setIsOpened]
+  );
+
+  useEffect(() => {
+    document.addEventListener('mousedown', handleVisibility);
+    document.addEventListener('focusin', handleVisibility);
+
+    return () => {
+      document.removeEventListener('mousedown', handleVisibility);
+      document.removeEventListener('focusin', handleVisibility);
+    };
+  }, [handleVisibility]);
 
   const mainNavConfig: NavItem[] = [
     {
@@ -99,7 +122,7 @@ const MainNav = ({
   });
 
   return (
-    <div className={styles.wrapper}>
+    <div ref={mainNavRef} className={styles.wrapper}>
       <input
         type="checkbox"
         name="main-nav__checkbox"
-- 
cgit v1.2.3

