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';34import Layout from '../components/layout';5import RandomComponent from '../components/randomComponent';67const RandomPage = () => (8 <Layout>9 <Location>10 {locationProps => <RandomComponent {...locationProps} />}11 </Location>12 </Layout>13);1415export default RandomPage;
Create a component inside the src/components
folder:
js
1import React from 'react';23const RandomComponent = ({ location }) => (4 <div>5 <p>{location}</p>6 </div>7);89export default RandomComponent;