Enea Xharja Logo

How to Get the Current Page URL in Gatsby

Gatsby uses Reach Router under the hood to handle routing. If you want to provide location anywhere in your app, you need to use the React Router's Location Component.

Create a page inside the src/pages folder:

js
1import React from 'react';
2import { Location } from '@reach/router';
3
4import Layout from '../components/layout';
5import RandomComponent from '../components/randomComponent';
6
7const RandomPage = () => (
8 <Layout>
9 <Location>
10 {locationProps => <RandomComponent {...locationProps} />}
11 </Location>
12 </Layout>
13);
14
15export default RandomPage;

Create a component inside the src/components folder:

js
1import React from 'react';
2
3const RandomComponent = ({ location }) => (
4 <div>
5 <p>{location}</p>
6 </div>
7);
8
9export default RandomComponent;
© 2021 Enea Xharja