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

Sometimes, we want to check history previous location before goBack() with React Router v4.

In this article, we’ll look at how to check history previous location before goBack() with React Router v4.

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

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.

Conclusion

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.