How to get previous url in react gatsby

Profer picture Profer · Mar 1, 2019 · Viewed 7.9k times · Source

I am pretty much familiar with the React.js but new to Gatsby.

I want to detect the previous page URL in Gatsby?

Answer

Soroush Chehresa picture Soroush Chehresa · Mar 1, 2019

You can pass down state using the Link component:

import React from 'react';
import { Link } from 'gatsby';

const PrevPage = () => (
  <div>
    <Link
      to={`/nextpage`}
      state={{ prevPath: location.pathname }}
    >
      Next Page
    </Link>
  </div>
)

const NextPage = (props) => (
  <div>
    <p>previous path is: {props.location.state.prevPath}</p>
  </div>
);

Then you have access to prevPath from this.props.location.state in the next page.