iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛤️

A Note on How to Get the Current Path (Location) in Next.js and Gatsby

に公開

Recently, I've started using Next.js and Gatsby more seriously, and I'm really feeling the excellence of how they handle routing.

Previously, I used to write React "vanilla" (do people say that? lol), install React Router, and diligently code the routing logic myself.

However, when I actually wanted to create breadcrumbs or change the UI based on the location, I wasn't sure how to retrieve the current path. So, I looked into how to do it in both Next.js and Gatsby.

Getting the path in Next.js

In Next.js, a hook called useRouter is provided in next/router. You can use this to easily retrieve the current path.

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.asPath === href ? 'red' : 'black',
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink

Source: https://nextjs.org/docs/api-reference/next/router#userouter

Getting the path in Gatsby

In Gatsby, the routing is handled by @reach/router.
It seems there is no need to install it separately; you can just call it and use it directly.

import { useLocation } from "@reach/router"

const useAnalytics = (props) => {
  const location = useLocation();

  useEffect(() => {
    // Send pageview to Google Analytics
    ga.send(['pageview', location.pathname]);
  }, [])
}

Source: https://reach.tech/router/api/useLocation

Reference: https://www.gatsbyjs.com/docs/reach-router-and-gatsby/

Conclusion

I recently started using Next.js, and I've been amazed at the convenience of a framework where things I used to implement manually by selecting various libraries are built-in so easily.

I can't see myself choosing any other options now.

Discussion