diff --git a/src/components/NavBar.js b/src/components/NavBar.js index c7fe9bb..fc4c25a 100644 --- a/src/components/NavBar.js +++ b/src/components/NavBar.js @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useRef } from "react"; import Button from "react-bootstrap/Button"; import Container from "react-bootstrap/Container"; import Form from "react-bootstrap/Form"; @@ -19,8 +19,11 @@ import useClickOutsideToggle from "../hooks/useClickOutsideToggle"; const NavBar = () => { const currentUser = useCurrentUser(); const setCurrentUser = useSetCurrentUser(); + const searchRef = useRef(null); - const { expanded, setExpanded, ref } = useClickOutsideToggle(); + const { expanded, setExpanded, ref } = useClickOutsideToggle({ + ignoreRefs: [searchRef], + }); const handleSignOut = async () => { try { @@ -125,11 +128,11 @@ const NavBar = () => { > Home - {currentUser ? loggedInIcons : loggedOutIcons}
{ +const useClickOutsideToggle = ({ ignoreRefs = [] } = {}) => { const [expanded, setExpanded] = useState(false); const ref = useRef(null); + useEffect(() => { const handleClickOutside = (event) => { - if (ref.current && !ref.current.contains(event.target)) { + const isOutside = ignoreRefs.every((ignoreRef) => ( + !ignoreRef.current || !ignoreRef.current.contains(event.target) + )); + + if (ref.current && !ref.current.contains(event.target) && isOutside) { setExpanded(false); } }; @@ -14,7 +19,8 @@ const useClickOutsideToggle = () => { return () => { document.removeEventListener("mouseup", handleClickOutside); }; - }, [ref]); + }, [ref, ignoreRefs]); + return { expanded, setExpanded, ref }; };