Skip to content

Commit

Permalink
#46 Fix issue with search input closing menu on click.
Browse files Browse the repository at this point in the history
  • Loading branch information
SandraBergstrom committed Jun 22, 2023
1 parent 364ef5b commit b36afc5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
9 changes: 6 additions & 3 deletions src/components/NavBar.js
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 {
Expand Down Expand Up @@ -125,11 +128,11 @@ const NavBar = () => {
>
<i className="fa-solid fa-house me-1"></i>Home
</NavLink>

{currentUser ? loggedInIcons : loggedOutIcons}
</Nav>
<Form className="d-flex">
<Form.Control
ref={searchRef}
type="search"
placeholder="Search"
className="me-2"
Expand Down
12 changes: 9 additions & 3 deletions src/hooks/useClickOutsideToggle.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { useEffect, useRef, useState } from "react";

const useClickOutsideToggle = () => {
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);
}
};
Expand All @@ -14,7 +19,8 @@ const useClickOutsideToggle = () => {
return () => {
document.removeEventListener("mouseup", handleClickOutside);
};
}, [ref]);
}, [ref, ignoreRefs]);

return { expanded, setExpanded, ref };
};

Expand Down

0 comments on commit b36afc5

Please sign in to comment.