- Published on
How to Get Current Path from Any Component in Gatsby
- Authors
- Name
- Ashik Nesin
- @AshikNesin
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