Enea Xharja

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:

import React from 'react';
import { Location } from '@reach/router';

import Layout from '../components/layout';
import RandomComponent from '../components/randomComponent';

const RandomPage = () => (
  <Layout>
    <Location>
      {(locationProps) => <RandomComponent {...locationProps} />}
    </Location>
  </Layout>
);

export default RandomPage;

Create a component inside the src/components folder:

import React from 'react';

const RandomComponent = ({ location }) => (
  <div>
    <p>{location}</p>
  </div>
);

export default RandomComponent;

Updated on February 05, 2021

Tagged with: gatsby, snippets


Profile picture

Hey there! I'm Enea, a web developer currently working at eqolot. Welcome to my little corner of the web, where I share my open collection of notes, code snippets, and resources on topics that interest me.

© 2021 Enea Xharja