'How can I redirect to previous page after login in react router?

I am looking to redirect to the page the user visited last after he/she finishes login, I am using react-router for this. How can I do that?



Solution 1:[1]

You can use query strings to accomplish this.

Add dependency query-string to your react app.

Whenever the user is trying to access a protected path, you have to redirect to the log-in screen if the user is not logged in yet. To do this you will do something like this.

history.push('/login');

But we can pass the previous as a query as follows. We can take the previous path using useLocation from react-router

const prevLocation = useLocation();
history.push(`/login?redirectTo=${prevLocation}`);

Now after successful login, we can get the query string that was passed in the previous path. We can set a default path if the previous path is null.

const handleSuccessLogin = () => {
      const location = useLocation();
      const { redirectTo } = queryString.parse(location.search);
      history.push(redirectTo == null ? "/apps" : redirectTo);
 };

This is IMO the best solution out there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Burhan