Skip to content

Commit

Permalink
clean up and create useClickOusideToggle.js
Browse files Browse the repository at this point in the history
  • Loading branch information
SandraBergstrom committed Jun 22, 2023
1 parent ecb04de commit 364ef5b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
18 changes: 3 additions & 15 deletions src/components/NavBar.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from "react";
import React from "react";
import Button from "react-bootstrap/Button";
import Container from "react-bootstrap/Container";
import Form from "react-bootstrap/Form";
Expand All @@ -14,25 +14,13 @@ import {
} from "../contexts/CurrentUserContext";
import Avatar from "./Avatar";
import axios from "axios";
import useClickOutsideToggle from "../hooks/useClickOutsideToggle";

const NavBar = () => {
const currentUser = useCurrentUser();
const setCurrentUser = useSetCurrentUser();

const [expanded, setExpanded] = useState(false);
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setExpanded(false);
}
};

document.addEventListener('mouseup', handleClickOutside)
return () => {
document.removeEventListener('mouseup', handleClickOutside)
}
}, [ref]);
const { expanded, setExpanded, ref } = useClickOutsideToggle();

const handleSignOut = async () => {
try {
Expand Down
21 changes: 21 additions & 0 deletions src/hooks/useClickOutsideToggle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect, useRef, useState } from "react";

const useClickOutsideToggle = () => {
const [expanded, setExpanded] = useState(false);
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setExpanded(false);
}
};

document.addEventListener("mouseup", handleClickOutside);
return () => {
document.removeEventListener("mouseup", handleClickOutside);
};
}, [ref]);
return { expanded, setExpanded, ref };
};

export default useClickOutsideToggle;

0 comments on commit 364ef5b

Please sign in to comment.