Redirect on Login and Logout
To complete the login flow we are going to need to do two more things.
- Redirect the user to the homepage after they login.
- And redirect them back to the login page after they logout.
We are going to use the withRouter
HOC and the this.props.history.push
method that comes with React Router v4.
Redirect to Home on Login
To use it in our src/containers/Login.js
, let’s replace the line that exports our component.
export default Login;
with the following:
export default withRouter(Login);
Also, import withRouter
in the header.
import { withRouter } from 'react-router-dom';
This Higher-Order Component adds the history
prop to our component. Now we can redirect using the this.props.history.push
method.
this.props.history.push('/');
Our updated handleSubmit
method in src/containers/Login.js
should look like this:
handleSubmit = async (event) => {
event.preventDefault();
try {
const userToken = await this.login(this.state.username, this.state.password);
this.props.updateUserToken(userToken);
this.props.history.push('/');
}
catch(e) {
alert(e);
}
}
Now if you head over to your browser and try logging in, you should be redirected to the homepage after you’ve been logged in.
Redirect to Login After Logout
Now we’ll do something very similar for the logout process. Since we are already using the withRouter
HOC for our App component, we can go ahead and add the bit that does the redirect.
Add the following to the bottom of the handleLogout
method in our src/App.js
.
this.props.history.push('/login');
So our handleLogout
method should now look like this.
handleLogout = (event) => {
const currentUser = this.getCurrentUser();
if (currentUser !== null) {
currentUser.signOut();
}
this.updateUserToken(null);
this.props.history.push('/login');
}
This redirects us back to the login page once the user logs out.
Now if you switch over to your browser and try logging out, you should be redirected to the login page.
You might have noticed while testing this flow that since the login call has a bit of a delay, we might need to give some feedback to the user that the login call is in progress. Let’s do that next.
If you liked this post, please subscribe to our newsletter and give us a star on GitHub.
For help and discussion
Comments on this chapterFor reference, here is the code so far
Frontend Source :redirect-on-login-and-logout