useRouterRouteIsActive()
A really simple hook for Next.js to check if the given page path is currently active.
This hook is especially useful when using structured URLs, i.e. /snippets
and /snippets/nextjs
both belonging to the same logical group.
import { useRouter } from "next/router";
export function useRouterRouteIsActive() {
const { asPath: currentPath } = useRouter();
return function (to) {
if (currentPath === "/" || to === "/") {
return to === currentPath;
}
return currentPath.startsWith(to);
};
}
Usage
- Given the current page is
/snippets/use-router-route-is-active
, the output would be “active”. - Given the current page is
/not-snippets
, the output would be “inactive”.
function Component() {
const isActive = useRouterRouteIsActive();
return <div>{isActive("/snippets") ? "active" : "inactive"}</div>;
}