How to Get the Current Page URL in Gatsby

Updated:

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:

// src/pages/RandomPage.js

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:

// src/components/RandomComponent.js

import React from "react";

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

export default RandomComponent;