Can redirect go back to previous page? #10169
Replies: 3 comments 4 replies
-
@tophboogie You can either try to get the |
Beta Was this translation helpful? Give feedback.
-
I was having the same problem i wanted to redirect back to previous route (with all search params) from action. the way it worked for me was: From the route i wanted to be redirected I had a
then we can get get const location = useLocation();
const redirectTo = location.state?.from; and pass |
Beta Was this translation helpful? Give feedback.
-
If you want to redirect the user to the previous page after a successful API call using react-router-dom's Redirect component, you can achieve this by storing the previous URL in the state or in a separate variable. Here's an example of how you can do it: import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
const MyComponent = () => {
const [redirectUrl, setRedirectUrl] = useState(null);
const handleSuccessfulSubmit = () => {
// Do your API call logic here
setRedirectUrl(document.referrer);
};
return (
<>
{redirectUrl && <Redirect to={redirectUrl} />}
<form onSubmit={handleSuccessfulSubmit}>
{/* Your form */}
</form>
</>
);
}; In the above code, setRedirectUrl(document.referrer) sets the redirectUrl state to the previous URL of the user, which is retrieved using document.referrer. This is assuming that the user is navigating to your current page from the previous page. Then, we use the Redirect component to redirect the user to the previous page when redirectUrl is truthy. I hope this helps! |
Beta Was this translation helpful? Give feedback.
-
Hello!
On some of my routes I have actions that I would like to return the user to the previous page after a successful post/put api call. With useNavigate I can do navigate(-1), but since hooks are required to be in the function component this seems cumbersome. Redirect is the preferred way to navigate in actions/loaders according to the docs, but it requires a url.
How can I go back to the previous page with redirect? It would be a great feature if redirect(-1) worked the same as useNavigate. Thank you!
Beta Was this translation helpful? Give feedback.
All reactions