From 9a3f2aba4d9e404ca933fea4979ee88b470f15f9 Mon Sep 17 00:00:00 2001 From: Kalyan Jyoti Borah Date: Fri, 2 Jun 2023 11:02:40 +0530 Subject: [PATCH] fix: close navbar on clicking outside (#788) Co-authored-by: Tamal Das --- src/components/Footer.jsx | 3 +- src/components/Navbar.jsx | 200 +++++++++++++++++--------------- src/context/MilanState.jsx | 1 + src/utils/clickAwayListener.jsx | 23 ++++ 4 files changed, 129 insertions(+), 98 deletions(-) create mode 100644 src/utils/clickAwayListener.jsx diff --git a/src/components/Footer.jsx b/src/components/Footer.jsx index 3b3089f4..8c414f14 100644 --- a/src/components/Footer.jsx +++ b/src/components/Footer.jsx @@ -202,11 +202,10 @@ const Footer = () => { href="https://github.com/IAmTamal/Milan" target="_blank" rel="noreferrer" - className="underline-animation" + className="underline-animation" > here -

)} diff --git a/src/components/Navbar.jsx b/src/components/Navbar.jsx index eef39146..87363948 100644 --- a/src/components/Navbar.jsx +++ b/src/components/Navbar.jsx @@ -9,13 +9,15 @@ import Modal from "./Modal"; import { FaBars } from "react-icons/fa"; import { IoMdClose } from "react-icons/io"; import Button from "./Button"; +import ClickAwayListener from "../utils/clickAwayListener"; const Navbar = () => { const navigate = useNavigate(); const location = useLocation(); const { isSignUpModalOpen, toggleSignUpModal } = useContext(MilanContext); const { isSignInModalOpen, toggleSignInModal } = useContext(MilanContext); - const { isNavbarOpen, toggleNavbar } = useContext(MilanContext); + const { isNavbarOpen, setIsNavbarOpen, toggleNavbar } = + useContext(MilanContext); const handleNavigate = () => { if (Cookies.get("token")) { @@ -35,108 +37,114 @@ const Navbar = () => { return ( <> - + + {isSignUpModalOpen && (
diff --git a/src/context/MilanState.jsx b/src/context/MilanState.jsx index 829a1f66..a63607ad 100644 --- a/src/context/MilanState.jsx +++ b/src/context/MilanState.jsx @@ -57,6 +57,7 @@ const MilanState = (props) => { isSignInModalOpen, toggleSignInModal, isNavbarOpen, + setIsNavbarOpen, toggleNavbar, }} > diff --git a/src/utils/clickAwayListener.jsx b/src/utils/clickAwayListener.jsx new file mode 100644 index 00000000..3d2b33fa --- /dev/null +++ b/src/utils/clickAwayListener.jsx @@ -0,0 +1,23 @@ +import React, { useEffect } from "react"; + +export default function ClickAwayListener(props) { + const { children, onClickAway } = props; + + useEffect(() => { + function handleClick(event) { + // Check if the clicked element is inside the component + if (!event.target.closest(".click-away-listener")) { + // If it's not, call the onClickAway function + onClickAway(); + } + } + + document.addEventListener("mousedown", handleClick); + + return () => { + document.removeEventListener("mousedown", handleClick); + }; + }, [onClickAway]); + + return
{children}
; +}