How to detect previous path in React Router?

Sometimes, we want to detect previous path in React Router.

In this article, we’ll look at how to detect previous path in React Router.

How to detect previous path in React Router?

To detect previous path in React Router, we can set the state property to an object with the location.pathname as the value.

For instance, we write

<Link to={{ pathname: "/nextpath", state: { prevPath: location.pathname } }}>
  Example Link
</Link>;

to set the to prop of the Link component to an object with the state property set to { prevPath: location.pathname }.

location.pathname has the value of the current path, which will become the previous path when we go to /nextpath.

Then we can get the value of prevPath from this.props.location.state if we go to the component that renders /nextPath.

Conclusion

To detect previous path in React Router, we can set the state property to an object with the location.pathname as the value.