Skip to content
Advertisement

React Router – How to pass previous location pathname to current

Is it possible to pass the previous path to current location?

For instance, I have 2 Routes. Home / and Profile /profile

If I am In Profile route and I go to Home route, now I am inside Home route, how do I get access to previous pathname which was /profile ?

Something like:

JavaScript

This is how I structure my router with custom routes

JavaScript

ProtectedRoute.js

JavaScript

Advertisement

Answer

Finally solved it. To anyone wondering how to pass state to route, this is how I did it.

By setting state when using Link or NavLink

<= v5 usage:

JavaScript

Or with history.push method

JavaScript

Now I have access to states passed to route

JavaScript

Update: On react router v6 there have been a few syntax changes. Check on this Codesandbox for example

v6 usage:

JavaScript
Advertisement