Skip to content

Commit

Permalink
fix: calculate active nav menu items with location.pathname
Browse files Browse the repository at this point in the history
  • Loading branch information
csr632 committed Dec 7, 2023
1 parent d08ecf5 commit 8122965
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions packages/theme-doc/src/Layout/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useContext, useMemo } from 'react'
import { Menu, Dropdown } from 'antd'
import { Link, matchPath, PathPattern } from 'react-router-dom'
import { Link, matchPath, PathPattern, useLocation } from 'react-router-dom'
import {
MenuUnfoldOutlined,
MenuFoldOutlined,
Expand All @@ -26,11 +26,16 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
const { render: renderLocaleSelector } = useLocaleSelector()
const themeCtxValue = useThemeCtx()
const {
loadState: { routePath },
resolvedLocale: { locale, localeKey },
resolvedLocale: { locale },
staticData,
} = themeCtxValue

// use location.pathname instead of loadState.routePath
// to calculate the active nav menu items
// because loadState.routePath may have param placeholder like /users/[uid]
// and it can't tell difference between /users/1 and /users/2
const { pathname } = useLocation()

const renderLogo = (() => {
const logoLink = (() => {
let result: string | undefined | null
Expand Down Expand Up @@ -73,7 +78,7 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
const result = (resolvedTopNavs ?? [])
.map(getActiveKeyIfMatch)
.filter(Boolean)
if (!result.includes(routePath)) result.push(routePath)
if (!result.includes(pathname)) result.push(pathname)
return result as string[]

function getActiveKeyIfMatch(item: MenuConfig) {
Expand Down Expand Up @@ -113,17 +118,15 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
} else {
actualMatcher = matcher
}
// use loadState.routePath instead of location.pathname
// because location.pathname may contain trailing slash
return !!matchPath(actualMatcher, routePath)
return !!matchPath(actualMatcher, pathname)
} else {
return matcher.some((oneMatcher) => {
return !!matchPath(oneMatcher, routePath)
return !!matchPath(oneMatcher, pathname)
})
}
}
}
}, [routePath, resolvedTopNavs])
}, [pathname, resolvedTopNavs])

return (
<header className={s.header}>
Expand Down

0 comments on commit 8122965

Please sign in to comment.