#Get current page name
1 messages · Page 1 of 1 (latest)
Hi @ripe steppe. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To get the current route name in a Next.js component, you can use the useRouter hook from the next/router package. The router object returned by this hook contains a pathname property, which represents the path for the current route file that comes after /pages. Here's an example of how to use it:
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const currentRoute = router.pathname;
return <p>Current route: {currentRoute}</p>;
}
export default MyComponent;
In this example, if you were on the home page with the route /, the currentRoute variable would contain the value '/'.
Source: Next.js Documentation - useRouter (https://nextjs.org/docs/pages/api-reference/functions/use-router#router-object)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@ripe steppe kapa.ai is still learning and improving, please let us how it did by reacting below
@tidal parrot How would I get the current route name from the router, e.g. if I was on the home-page with the route / - how would I get that in a component using the app directory?
Let me check the knowledge base for you. One moment! :books:
To get the current route name in a Next.js component using the app directory, you can use the usePathname hook from the next/navigation package. Here's an example of how to use it:
'use client';
import { usePathname } from 'next/navigation';
function MyComponent() {
const currentRoute = usePathname();
return <p>Current route: {currentRoute}</p>;
}
export default MyComponent;
In this example, if you were on the home page with the route /, the currentRoute variable would contain the value '/'.