From ea8aafeae3be040737567acc7f8b048d6198cdc5 Mon Sep 17 00:00:00 2001 From: Lim SangHyun Date: Fri, 25 Nov 2022 17:05:34 +0900 Subject: [PATCH] Highlight selected nav menu --- src/App/Navbar.tsx | 69 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/src/App/Navbar.tsx b/src/App/Navbar.tsx index ec577cf..ba235aa 100644 --- a/src/App/Navbar.tsx +++ b/src/App/Navbar.tsx @@ -1,4 +1,5 @@ -import { ReactElement, useState } from 'react' +import { ReactElement, useEffect, useState } from 'react' +import { useLocation, useNavigate } from 'react-router-dom' import { Collapse, Navbar, @@ -11,12 +12,55 @@ import { NavLink, Form, } from 'reactstrap' + +import { COLOR } from 'consts' + import githubIcon from 'images/GitHub-Mark-Light-64px.png' import routes from '../routes' import { RouteType } from 'types' const RouteItem = ({ route }: { route: RouteType }): ReactElement => { const [isOpen, setIsOpen] = useState(false) + const { pathname } = useLocation() + const [selectedIndex, setSelectedIndex] = useState(-1) + const navigate = useNavigate() + + const SubItem = ({ + name, + href, + index, + }: { + name: string + href: string + index: number + }): ReactElement => { + useEffect(() => { + if (pathname.includes(href)) { + setSelectedIndex(index) + } + }, []) + + return ( + { + navigate(href) + }} + > + {name} + + ) + } + + useEffect(() => { + if (false === pathname.includes(route.path)) { + setSelectedIndex(-1) + } + }, [pathname]) + return ( { onMouseLeave={(): void => setIsOpen(false)} toggle={(): void => setIsOpen(!isOpen)} > - + -1 ? COLOR.primary : 'white', + }} + onClick={(): void => { + navigate(`${route.path}${route.items[0].path}`) + }} + > {route.name} {route.items.map((item, j) => { + const path = `${route.path}${item.path}` + return ( - - {item.name} - + index={j} + name={item.name} + href={path} + /> ) })}