diff options
| author | Armand Philippot <git@armandphilippot.com> | 2022-02-01 23:51:33 +0100 | 
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2022-02-01 23:51:33 +0100 | 
| commit | 9eb5d1edcf7f3b0e525e90b98afe416c4be35be0 (patch) | |
| tree | 46e1919dbce896e76de966d2264e34913e3bb0ab /src/components/MainNav/MainNav.tsx | |
| parent | 98acc4836ce1d6b901cb6e7d524fe9ea164bf5e0 (diff) | |
chore: close mainNav on click outside or route change
Diffstat (limited to 'src/components/MainNav/MainNav.tsx')
| -rw-r--r-- | src/components/MainNav/MainNav.tsx | 27 | 
1 files changed, 25 insertions, 2 deletions
| 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" | 
