Home > OS >  How to get current pathname using router from next/navigation?
How to get current pathname using router from next/navigation?

Time:11-28

I'm using the experimental appDir in Next.js 13, where they have replaced next/router with next/navigation, so I imported the useRouter hook accordingly. I do not see the property pathname in the router, which does exist in next/router's router.

Property 'pathname' does not exist on type 'AppRouterInstance'

My use case is to highlight the link in my navbar that the user is currently on. This is what I tried:


import Link from "next/link";
import { useRouter } from 'next/navigation';


const StyledNavLink: React.FC<NavLinkProps> = ({ to, children }) => {
  const router = useRouter();
  ...
  return (
    <Link href={to} className={getNavLinkClass({isActive: router.pathname === to})}>
      {children}
    </Link>
  );
};

Is there anything I can do to get the current path name or something else to add my classes on the active link?

CodePudding user response:

The pathname in Next 13 has its hook called usePathname(). They say in useRouter()'s new documentation:

The pathname string has been removed and is replaced by usePathname().

That has been said, both usePathname() and useRouter() only work in a client component, which should have a "use client" string at the top:

The usePathname hook allows you to read the current URL pathname from a Client Component.

'use client';

import { usePathname } from 'next/navigation';

export default function Page() {
  const pathname = usePathname();
  return <div>{pathname}</div>;
}
  • Related