How to get previous url in react gatsby
Asked Answered
G

4

9

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

I want to detect the previous page URL in Gatsby?

Gamboge answered 1/3, 2019 at 9:53 Comment(4)
If it uses browser's history, the prev url should be saved in document.referrer I think.Cavalcade
Nopes it is blank. I am not getting anything inside it.Gamboge
Possible duplicate of How to get the previous page URL using JavaScript?Etam
@soroushchehresa No this is not a duplicate. Please refer the question. I have to do with gatsby and event I didn't put the javascript tag. And also gatsby build will not execute the window variable. So please take back your close vote.Gamboge
E
19

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.

Etam answered 1/3, 2019 at 11:14 Comment(7)
Thank you!!! There is no way to do this with gatsby and hence I will go with your above answerGamboge
@Gamboge Don't mention it ;)Etam
@Gamboge Why do you say there's no way to do this with Gatsby? This answer shows you how to do it with Gatsby's Link component (which builds on the Reach Router Link component).Syd
@Syd because the above answer is just a trick. If there is a way then Gatsby itself provide some prop or constant.Gamboge
@Gamboge How is it a trick? Gatsby itself provides the state prop on Link and provides the value passed to it to the page component of the following page. It's documented here..Syd
@Syd is correct. Passing state into the Link component is a Gatsby Link feature, which is extended from reach/router's api.Oder
This is wrong.. location.state persists.. so when you go to this page you will have that state set correctly but then if you navigate to another page and do a browser back the state will have this same value which is false.Lifeless
H
12

Full credit to @soroushchehresa's answer — this answer is just extras built upon it.

Gatsby will throw error during production build, since location is not available during server-side rendering. You could get around it by checking for window object first:

class Page extends React.Component {
  state = {
    currentUrl: '',
  }

  componentDidMount() {
    if (typeof window == 'undefined') return
    this.setState({ currentUrl: window.location.href })
  }

  render() {
    return (
      <Link to="..." state={{ prevUrl: this.state.currentUrl }}>
    )
  }
}

But this requires us to implement this on every page, which is tedious. Gatsby has already set up @reach/router for server-side rendering, so we can hook into its location props. Only router components get that props, but we can use @reach/router's Location component to pass it to other components.

With that, we can write a custom Link component that always pass previous url in its state:

// ./src/components/link-with-prev-url.js

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

const LinkWithPrevUrl = ({ children, state, ...rest }) => (
  <Location>
    {({ location }) => (
                      //make sure user's state is not overwritten
      <Link {...rest} state={{ prevUrl: location.href, ...state}}>
        { children }
      </Link>
    )}
  </Location>
)

export { LinkWithPrevUrl as Link }

Then we can import our custom Link component instead of Gatsby's Link:

-  import { Link } from 'gatsby'
+  import { Link } from './link-with-prev-url'

Now each Gatsby page component will get this previous url props:

const SomePage = ({ location }) => (
  <div>previous path is {location.state.prevUrl}</div>
);

You might also consider creating a container that store state for the client side & use the wrapRootElement or wrapPageElement in both gatsby-ssr.js and gatsby-browser.js.

Helgahelge answered 1/3, 2019 at 18:50 Comment(2)
Slick. I like it.Syd
I came across the initial answer by way of the Gatsby docs, actually, and was hoping to avoid the tedium. Thanks for expounding on it to create a streamlined approach—great idea! I was looking at the onRouteUpdate API in gatsby-browser.js which exposes location, prevLocation but, as far as I can tell, it only makes them available for use outside the scope of my Gatsby/React components.Tetrasyllable
L
11

These answers are partially correct. If you set state using link api then the state persists in browser history.

So if you go from Page1 to Page2 then the eg the state.prevUrl will correctly be set to Page1

But if then you go to Page3 from Page2 and then do a browser back then the state.prevUrl will still be Page1 which is false.

Best way I found to deal with this is to add something like this on the gatsby-browser.js

export const onRouteUpdate = ({ location, prevLocation }) => {
  if (location && location.state)
    location.state.referrer = prevLocation ? prevLocation.pathname : null
}

this way you will have always the previous url available on location.

Lifeless answered 23/10, 2019 at 13:47 Comment(0)
T
2

I resolved my problem with the below piece of code. Here is the ref link https://github.com/gatsbyjs/gatsby/issues/10410

// gatsby-browser.js
exports.onRouteUpdate = () => {
  window.locations = window.locations || [document.referrer]
  locations.push(window.location.href)
  window.previousPath = locations[locations.length - 2]
}

Now you can get previousPath can be accessed from anywhere.

Turtleback answered 6/7, 2021 at 6:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.