Skip to content

Commit

Permalink
Merge pull request #2369 from graphcommerce-org/fix/active-menu-item
Browse files Browse the repository at this point in the history
chore: resolve the issue with active menu items when two or more pages start with the same URL (GCOM-1482)
  • Loading branch information
paales authored Nov 20, 2024
2 parents 55c3134 + 706629e commit 92212d3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-pots-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphcommerce/next-ui': patch
---

Mark the menu item as active if router.asPath matches the href, or if the first URL segment matches, indicating it's the parent item.
15 changes: 9 additions & 6 deletions packages/next-ui/LayoutParts/DesktopNavBarItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { extendableComponent } from '../Styles/extendableComponent'

const { classes, selectors } = extendableComponent('DesktopNavItem', ['root', 'line'] as const)

export type DesktopNavItemLinkProps = LinkProps<'a'>
export type DesktopNavItemLinkProps = LinkProps<'a'> & {
active?: boolean
}
export type DesktopNavItemButtonProps = LinkProps<'div'> & {
onClick: LinkProps<'button'>['onClick']
active?: boolean
}

function isLinkProps(
Expand All @@ -19,7 +22,7 @@ export function DesktopNavItem(props: DesktopNavItemLinkProps | DesktopNavItemBu
const router = useRouter()

if (!isLinkProps(props)) {
const { onClick, children, sx = [], ...linkProps } = props
const { onClick, children, sx = [], active, ...linkProps } = props

return (
<Link
Expand All @@ -40,9 +43,9 @@ export function DesktopNavItem(props: DesktopNavItemLinkProps | DesktopNavItemBu
)
}

const { href, children, sx = [], ...linkProps } = props

const active = router.asPath.startsWith((href ?? '').toString())
const { href, children, sx = [], active, ...linkProps } = props
const activeValue =
typeof active === 'undefined' ? router.asPath.startsWith((href ?? '').toString()) : active

return (
<Link
Expand All @@ -67,7 +70,7 @@ export function DesktopNavItem(props: DesktopNavItemLinkProps | DesktopNavItemBu
background: (theme) => theme.palette.primary.main,
margin: '0 auto',
marginTop: '6px',
opacity: active ? 1 : 0,
opacity: activeValue ? 1 : 0,
}}
/>
</Link>
Expand Down

0 comments on commit 92212d3

Please sign in to comment.