usePathname현재 어떤 페이지가 활성화되어 있는 지를 확인해야 하는 상황이라면 어떻게 해야할까?
예를 들어, 활성화된 페이지에 따라 네비게이션 바에 있는 메뉴를 하이라이트 표시해야 한다고 가정해보자.
이 경우, Next.js에서는 usePathname이라는 hook을 사용할 수 있다.
먼저, usePathname을 import 시킨 후,
import { usePathname } from "next/navigation";
다음과 같이, usePathname 함수를 변수에 할당하여 사용하면 된다.
export default function NavLink({ href, children }) {
const path = usePathname();
return (
<Link
href={href}
className={
path.startsWith(href)
? `${classes.link} ${classes.active}`
: classes.link
}
>
{children}
</Link>
);
}
여기서, startsWith는 href로 시작하는 경로를 말한다.
만약 href를 /bunny로 설정했다면, /bunny를 비롯하여 /bunny/carrot 등의 모든 경로를 포함하는 것이다.
💡 usePathname는 client component에서만 작동하기 때문에, 코드 상단에 반드시
use client를 추가해야 한다.