Categories
React Answers

How to check history previous location before goBack() with React Router v4?

Spread the love

To check history previous location before goBack() with React Router v4, we can save the pathname from the previous location in the Link‘s to prop’s state property.

For instance, we write

<Link
  to={{ pathname: "/graph/1", state: { from: this.props.location.pathname } }}
/>;

to set the state to the value of the current URL before we click on the Link by setting state to { from: this.props.location.pathname }.

We can do the same with history.push by writing

history.push({
  pathname: "/graph/1",
  state: {
    from: this.props.location.pathname,
  },
});

this.props.location.pathname has the URL path of the current page.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *