#Get current page name

1 messages · Page 1 of 1 (latest)

ripe steppe
#

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?

tidal parrotBOT
#

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:

Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.

#

@ripe steppe kapa.ai is still learning and improving, please let us how it did by reacting below

ripe steppe
#

@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?

tidal parrotBOT
#

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 '/'.

Source: Next.js Documentation - App Router Migration (https://nextjs.org/docs/pages/building-your-application/upgrading/app-router-migration)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

Learn how to upgrade your existing Next.js application from the Pages Router to the App Router.