How to Get Current Path from Any Component in Gatsby

May 17, 2020

Under the hood Gatsbyjs uses reach router for client-side routing. So we can pretty easily get the current route from any component in Gatsby.

import { globalHistory } from "@reach/router"
const path = globalHistory.location.pathname

Quick Example

Let’s say you’ve Hello component that needs to be display 👋only if the current route is /

// Hello.jsx
import React from "react"
import { globalHistory } from "@reach/router"
const path = globalHistory.location.pathname

const Hello = () => {
    const path = globalHistory.location.pathname
    const isHomepage = path === '/'
    if(isHomepage){
        return "<p>👋</p>
    } 
    return null
}

export default Hello

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP