javascriptreactjsgatsbystatic-site

How to get previous url in react gatsby


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

I want to detect the previous page URL in Gatsby?


Solution

  • 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.