0

I'm making a page in NextJs, and would love to show the user which page they're on with some styling of the NavBar.

This seems super - Target Active Link when the route is active in Next.js ...however I'm using a mapped list to generate the NavBar.

Might anyone be able to help me out with how to use this with a map() function please? Here's my code, which works otherwise.

import Link from "next/link";

import styles from "../NavBarDesktop/NavBarDesktop.module.css";

import ButtonBase from "../button/buttonPrimary";
import MenuItems from "../../../data/MenuItems/MenuItems";

const NavBarDesktop = () => {

  return (
    <div className={styles.navBar}>
      <ul className={styles.navMenu}>
        {MenuItems.map((item) => (
          <li className={styles.navItem} key={item.id}>
            <Link href={item.path}>{item.title}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default NavBarDesktop;
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

From the link you posted, this wouldn't be any different when using map. All the map function is doing is looping over your MenuItems.

What you would need to do is check to see if the current item is the one you're looking at within your map callback function.

An example of what you could do:


import { useRouter } from 'next/router'

const NavBarDesktop = () => {
  const router = useRouter();

  return (
    <div className={styles.navBar}>
      <ul className={styles.navMenu}>
        {MenuItems.map((item) => {
          const activeStyle = item.path === router.pathname ? styles.activeNavItem : '';
          
          return (
            <li className={`${styles.navItem} ${activeStyle}`} key={item.id} >
              <Link href={item.path}>{item.title}</Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

What I'm doing here is checking to see if the item.path matches Next.js router.pathname. I use next/router because this should match up with what you are trying to use with Link. If they do match, then I want the current nav item that we are looking at to be the active one and so we add it as a class to your li element.

More info on next/router here: https://nextjs.org/docs/api-reference/next/router#router-object

You might need to play around with this to make sure it does match with what your href is.

timngyn
  • 101
  • 6