Reputation: 4769
How to store previous location
(route) in a constant and pass it through a query param?
I am using React router v5.
In my React (route) component I have a Link
import { Link } from 'react-router-dom';
<Link to={{ pathname: MyPage, search: `?redirectUrl=previous-route` }}>
Go to page
</Link>
I need to pass the previous location route to the next route (MyPage
) through the query param redirectUrl
.
<Link to={{ pathname: MyPage, search: `?redirectUrl=${<----- My previous route value here}` }}>
Go to page
</Link>
How do I manage that?
Upvotes: 2
Views: 2072
Reputation: 202667
Use the useLocation
hook to get the current location to pass along as the previous location for the next page.
import { Link, useLocation } from 'react-router-dom';
...
const { pathname } = useLocation();
...
<Link to={{ pathname: MyPage, search: `?redirectUrl=${pathname}` }}>
Go to page
</Link>
Upvotes: 2