Skip to content

Commit

Permalink
✨ close dropdown on click outside itself
Browse files Browse the repository at this point in the history
  • Loading branch information
heytulsiprasad committed Sep 11, 2020
1 parent f8f9bb5 commit a336b30
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/components/Profile/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,38 @@ const Overlay = styled.div`
`;

const Navbar = () => {
const topbarRef = React.useRef(null);
const [isOpen, setIsOpen] = React.useState(false);
const toggleDropdown = () => setIsOpen(!isOpen);

// Change state when clicked outside of dropdown
React.useEffect(() => {
if (isOpen) {
const handleClickOutside = (event) => {
if (topbarRef.current && !topbarRef.current.contains(event.target)) {
console.log("Hit");
setIsOpen(false);
}
};

// Add event listener
document.addEventListener("mousedown", handleClickOutside);

return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}
}, [topbarRef, isOpen]);

return (
<NavbarContainer>
<Logo to="/dash">
<img src={Icon} alt="product-logo" />
<h1>Talk.to</h1>
</Logo>
<Dropdown>
<Topbar onClick={toggleDropdown}>
<Topbar ref={topbarRef} onClick={toggleDropdown}>
<img
className="person-profile"
src={Person}
Expand All @@ -116,11 +137,11 @@ const Navbar = () => {
{isOpen && (
<Overlay>
<div className="profile option">
<span class="material-icons">account_circle</span>
<span className="material-icons">account_circle</span>
<h2 className="option-text">My Profile</h2>
</div>
<div className="logout option">
<span class="material-icons">login</span>
<span className="material-icons">login</span>
<h2 className="option-text">Logout</h2>
</div>
</Overlay>
Expand Down

0 comments on commit a336b30

Please sign in to comment.