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:

const Home = (props) => {
   console.log(props.location.state.previousPath) // How to access previous path? 
}

This is how I structure my router with custom routes

const App = () => (
  <Router history={history}>
    <main className="min-h-screen">
      <NavBar />
      <Switch>
         <PublicRoute path={ROUTE.REGISTER} component={Register} />
         <PublicRoute path={ROUTE.LOGIN} component={Login} />
         <ProtectedRoute path={ROUTE.HOME} exact component={Home} />
         <ProtectedRoute path={ROUTE.PROFILE} component={Profile} />
         <Route component={PageNotFound} />
       </Switch>
     </main>
   </Router>
)

ProtectedRoute.js

const ProtectedRoute = ({ isAuth, component: Component, path, ...rest }) => {
    return (
        <Route
            {...rest}
            component={(props) => {
                // ANY WAY TO ACCESS IT HERE THEN PASS IT TO COMPONENT?
                return isAuth ? <Component {...props} /> : <Redirect to={LOGIN} />
            }}
        />
    );
}

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:

const { pathname } = useLocation();

<Link 
    to={{ 
    pathname: '/', 
    state: { from: pathname } // or any property you like to add
  }}
> 
   Home
</Link>

Or with history.push method

const history = useHistory();
const { pathname } = useLocation();

history.push('/', { from: pathname, someOtherProp: '' }) 
                  // second argument for passing state

Now I have access to states passed to route

const Home = (props) => {
   console.log(props.location.state.from);
}

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

v6 usage:

const navigate = useNavigate();
const { pathname } = useLocation();

// Using hook
navigate("/", { state: { previousPath: pathname } });

// using Link component
<Link to="/" state={{ previousPath: pathname }}>

Advertisement