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
x
4
1
const Home = (props) => {
2
console.log(props.location.state.previousPath) // How to access previous path?
3
}
4
This is how I structure my router with custom routes
JavaScript
1
15
15
1
const App = () => (
2
<Router history={history}>
3
<main className="min-h-screen">
4
<NavBar />
5
<Switch>
6
<PublicRoute path={ROUTE.REGISTER} component={Register} />
7
<PublicRoute path={ROUTE.LOGIN} component={Login} />
8
<ProtectedRoute path={ROUTE.HOME} exact component={Home} />
9
<ProtectedRoute path={ROUTE.PROFILE} component={Profile} />
10
<Route component={PageNotFound} />
11
</Switch>
12
</main>
13
</Router>
14
)
15
ProtectedRoute.js
JavaScript
1
12
12
1
const ProtectedRoute = ({ isAuth, component: Component, path, rest }) => {
2
return (
3
<Route
4
{rest}
5
component={(props) => {
6
// ANY WAY TO ACCESS IT HERE THEN PASS IT TO COMPONENT?
7
return isAuth ? <Component {props} /> : <Redirect to={LOGIN} />
8
}}
9
/>
10
);
11
}
12
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
1
11
11
1
const { pathname } = useLocation();
2
3
<Link
4
to={{
5
pathname: '/',
6
state: { from: pathname } // or any property you like to add
7
}}
8
>
9
Home
10
</Link>
11
Or with history.push
method
JavaScript
1
6
1
const history = useHistory();
2
const { pathname } = useLocation();
3
4
history.push('/', { from: pathname, someOtherProp: '' })
5
// second argument for passing state
6
Now I have access to states passed to route
JavaScript
1
4
1
const Home = (props) => {
2
console.log(props.location.state.from);
3
}
4
Update: On react router v6 there have been a few syntax changes. Check on this Codesandbox for example
v6 usage:
JavaScript
1
10
10
1
const navigate = useNavigate();
2
const { pathname } = useLocation();
3
4
// Using hook
5
navigate("/", { state: { previousPath: pathname } });
6
7
// using Link component
8
<Link to="/" state={{ previousPath: pathname }}>
9
10