0

I'm using nextjs Link and a antd layout component to design my navigation pane. I want to highlight the nav menu item whenever I'm on a specific page.How do i achieve this? code for my navigation menu

blue whale
  • 21
  • 2
  • Please do _not_ use images for code. Add any relevant code as a code snippet to your question. – juliomalves Jul 28 '21 at 11:50
  • 1
    Get the page's URL path (https://stackoverflow.com/questions/58022046/get-url-pathname-in-nextjs) and check it against the Link href in a ternary statement. Like the CSS className would be `pagePath == Link.href ? highlighted : not-highlighted` – i-know-nothing Jul 28 '21 at 19:00

1 Answers1

0

For future people looking at a quick answer:

import { useRouter } from 'next/router';
import { useState, useEffect } from "react";

In your menu component:

const router = useRouter()
const [current, setCurrent] = useState(router.pathname);
useEffect ( () => {
  setCurrent(router.pathname)
}, [router.pathname])

Then the antd menu item:

<Menu
  selectedKeys={[current]}
  items={items}
/>
Nicolas Bernard
  • 155
  • 2
  • 12