Reputation: 797
I am trying to do something very simple in a React app. I want a "Back" button to take the user to the previous page UNLESS the user has arrived from a specific page, and in that case "Back" will route them to a different page - something like:
const navigate = useNavigate();
if (lastPage === XYZ) {
navigate('/home');
} else {
navigate(-1);
}
My issue is that I can't work out how to get hold of the lastPage in react-router-dom v6 (where useHistory has been depricated). Thanks!
Upvotes: 2
Views: 2107
Reputation: 203418
From the "specific" page you should send some "state" to indicate that's where it navigated from.
Example:
Using Link
component
<Link to="/newPage" state={{ fromSpecificPage: true }} />
Using Navigate
component
<Navigate to="/newPage" state={{ fromSpecificPage: true }} />
Using navigate
function
const navigate = useNavigate();
navigate("/newPage", { state: { fromSpecificPage: true } });
Then on the page you want to conditionally handle the back navigation check this specific route state that was possibly passed.
import { useLocation, useNavigate } from 'react-router-dom';
...
const { state } = useLocation();
const navigate = useNavigate();
...
const { fromSpecificPage } = state || {};
if (fromSpecificPage) {
navigate('/home', { replace: true });
} else {
navigate(-1);
}
Upvotes: 2