nextjs check path in page

Next.js Check Path in Page

If you want to check the path in a Next.js page, you can use the useRouter hook provided by the next/router package. This hook provides access to the current URL and allows you to check the path and query parameters.

Example Code:


import { useRouter } from 'next/router'

function MyPage() {
  const router = useRouter()

  console.log(router.pathname) // logs "/mypage"
  console.log(router.query) // logs { id: '123' }

  return (
    <div>
      <h1>My Page</h1>
      <p>ID: {router.query.id}</p>
    </div>
  )
}

export default MyPage

In this example, we import the useRouter hook and use it inside the MyPage component. We log the current pathname and query parameters to the console, and then use them to render some content on the page. The router.pathname property gives us the current path, which in this case is "/mypage". The router.query property gives us an object with the query parameters, which in this case is { id: '123' }.

You can also use the useRouter hook outside of a page component, such as in a custom hook or utility function. In this case, you need to wrap your code in a useEffect hook and listen for route changes:

Example Code:


import { useEffect } from 'react'
import { useRouter } from 'next/router'

function usePath() {
  const router = useRouter()

  useEffect(() => {
    console.log('Path changed:', router.pathname)
  }, [router.pathname])

  return router.pathname
}

export default usePath

In this example, we create a custom hook called usePath that logs the current path whenever it changes. We wrap our code in a useEffect hook and pass in the router.pathname property as a dependency, so that our code is re-run whenever the path changes. We then return the current path from our custom hook.

Overall, the useRouter hook provides a simple and convenient way to check the current path in a Next.js page or custom hook. It is a powerful tool that can help you build dynamic and responsive applications with ease.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe