Skip to content

Commit

Permalink
adding event listener to close navbar dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
s2sharpit committed Jun 28, 2023
1 parent 6612fd4 commit c16b7ee
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions src/components/main-nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,63 @@ import { cn } from "@/lib/utils";
import { NavItem } from "@/types/nav";
import Image from "next/image";
import Link from "next/link";
import * as React from "react";
import { useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { BiMenuAltRight } from "react-icons/bi";
import { MdOutlineClose } from "react-icons/md";
import { buttonVariants } from "./ui/button";
import { ThemeToggle } from "./theme-toggle";
import { buttonVariants } from "./ui/button";

interface MainNavProps {
items?: NavItem[];
}

export function MainNav({ items }: MainNavProps) {
const [toggle, setToggle] = useState<boolean>(false);
const menuRef = useRef<HTMLDivElement>(null);

const handleClose = useCallback(
(e: any) => {
if (menuRef.current && !menuRef.current?.contains(e.target)) {
setToggle(false);
}
},
[menuRef]
);

useEffect(() => {
if (!toggle) return;
window.addEventListener("click", handleClose);
window.addEventListener("scroll", handleClose);

return () => {
window.removeEventListener("click", handleClose);
window.removeEventListener("scroll", handleClose);
};
}, [handleClose, toggle]);

return (
<div className="flex min-w-full justify-between">
<div ref={menuRef} className="flex min-w-full justify-between">
{/* desktop width navbar */}
<div className="flex w-full justify-between">
{/* Brand Logo | home page link */}
<div className="relative mr-6 flex h-[60px] w-[130px] shrink-0 flex-row items-center">
{/* logo hidden on dark mode */}
<Link href="/" className="w-100 block dark:hidden">
<Image src="/logo-v3-full.png" sizes="(max-width: 768px) 100vw" fill={true} alt="logo" />
<Image
src="/logo-v3-full.png"
sizes="(max-width: 768px) 100vw"
fill={true}
alt="logo"
/>
</Link>
{/* logo hidden on light mode */}
<Link href="/" className="w-100 hidden dark:block">
<Image src="/logo-v3-full-dark.png" sizes="(max-width: 768px) 100vw" fill={true} alt="logo" />
<Image
src="/logo-v3-full-dark.png"
sizes="(max-width: 768px) 100vw"
fill={true}
alt="logo"
/>
</Link>
</div>
{/* container with both nav links and Logos */}
Expand Down

0 comments on commit c16b7ee

Please sign in to comment.