Is there any way to find the path of the page that a user is on on a Gatsby site and store it in a const
so that it can be checked next to the current path the user is on? In other words if they're on the /about
page, and are clicking a link to navigate to the /contact
page, I need to get the paths of both so that I can check them against each other. I know I can get location.pathname
for the current url, but how do I find the path that they are navigating to when the click a link?

- 568
- 10
- 33
-
Are you using any library for the routes? If not what's the harm in using click event handler on the links? ā Anand Bhushan Oct 27 '20 at 01:22
-
Iām not using anything special, no. I just need to be able to check the target path compared to the current path. ā Jesse Winton Oct 27 '20 at 01:26
2 Answers
Since your code structure isn't clear. Assuming a simple anchor tag, you can do something like this:-
<a href="/new/link" onClick={getHref}>New Link</a>
And in your getHref
method
function getHref(event){
console.log(event.target.href); // should log '/new/link'
}
Check if this works in your case.
Please forgive for any typo, I havent validated it.

- 765
- 8
- 18
Gatsby exposes props
(because it extends from @reach/router
from React) by default on the top-level components (this means pages). You can pass it to the child components as you wish or store it in a const
or in a React's state.
Without knowing any page structure, I'll provide something dummy as an example:
import React from "react"
import { graphql } from "gatsby"
const YourPage = ({ location, data }) => {
console.log('your page is ', location.pathname)
return <div>Dummy content</div>
}
export default Page
export const query = graphql`
query PageQuery {
site {
siteMetadata {
siteURL
}
}
}
`
Your information is stored under props.location
, that's why you can destructure it in the component's declaration.
In the case above, I've used pathname
property but you have a bunch exposed. Check it out to find out which one fits your requirements.

- 28,630
- 6
- 39
- 67