2

I have more than 5 categories that have different products in them. So in my pages folder, I have a file named [...slug].js. All this URL's have different names;

For Ex these are my URL;

  • /phones
  • /laptops
  • /tv

..and I want to add class names to these links when they are active so that I can add some styling on them.

  import Link from 'next/link';
  import { useRouter } from 'next/router';

  export const Header = () => {
    const router = useRouter();

    return (
      <header>
        <Link href="/phones">
          <a className={router.pathname == "/phones" ? "active" : ""}>
            Phones
          </a>
        </Link>
        <Link href="/laptops">
          <a className={router.pathname == "/laptops" ? "active" : ""}>
            Laptops
          </a>
        </Link>
        <Link href="/tv">
          <a className={router.pathname == "/tv" ? "active" : ""}>
            TV
          </a>
        </Link>
      </header>
    )
  }

However, when I check the router.pathname when I navigate to those links, the URL is appearing as /[...slug]. Is there any other way to get the actual URL name for dynamic URLs on NextJS

Rinael
  • 133
  • 3
  • 12
  • 3
    You want to use `router.asPath` instead. I'd recommend a read through https://nextjs.org/docs/api-reference/next/router#router-object. – juliomalves Dec 29 '21 at 20:31

1 Answers1

0

You need the path as shown in the browser including the search params,

  const { data: genreData } = useGetGenreQuery({});
  const { asPath } = useRouter();


  <Link
      key={key}
      className={asPath == `/genre/${item.id}` ? "active" : ""}
      href={`/genre/${item.id}`}>
      <li className="cursor-pointer"> {item.name} </li>
  </Link>