Redirect to previous path on login - React Router v4
Following this example you can make a component PrivateRoute
to wrap Route
and use that whenever you need a route that requires auth.
This is the component code from the example.
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ?
(<Component {...props}/>)
:
(
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
)}
/>
)
Previous answers are not detail enough.
Solution:
Router
<BrowserRouter basename={BASE_NAME}>
<Switch>
{publicRouteList()}
<Route exact key="login" path="/login" component={Login} />
{getLoggedRouteList(state.logged)}
<Redirect key="redirect-login" to="/login" />
</Switch>
</BrowserRouter>
getLoggedRouteList
const getLoggedRouteList = (logged) => {
if (!logged) {
return (
<Route
key="wait-login"
render={props => {
return (
<Redirect
to={{
pathname: '/login',
state: { from: props.location },
}}
/>
);
}}
/>
);
}
const output = [];
output.push(
/* Here place route list that need logged */
);
return output;
}
Login Component
class Login extends React.Component {
login = async param => {
const { location } = this.props;
const { state } = location;
/* Here place request login api */
// go to state.from if set before
if (state && state.from) {
history.replace(state.from);
}
// else go to home
else {
history.replace('/');
}
}
}
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 lastLocation = useLocation();
history.push(`/login?redirectTo=${lastLocation}`);
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);
};
Inspired by https://ui.dev/react-router-v4-query-strings/