Redirect To Route Within Function React Router Dom
I have a button with a click event that calls a function that makes an API to login a user, once a user has been successfully logged in. I want to redirect the user to /overview. I
Solution 1:
Since LoginCard
is a child component of Login
it will not get access to the route props
automatically. You can either change your Route
to the following, and pass down the history
prop from Login
to LoginCard
:
<Routepath="/login"component={Login} />
Or you can use the withRouter
HOC to inject the route props
into the LoginCard
component.
constLoginCard = props => {
const loginService = newLoginService();
consthandleLogin = () => {
loginService.login(email, password).then(response => {
props.history.push("/overview");
});
};
return (
<divclassName="Login"><ButtononClick={handleLogin}>Login</Button></div>
);
};
exportdefaultwithRouter(LoginCard);
Solution 2:
You can return it conditionally in your render method like
if(this.state.authenticated){
return <Redirect to={{ pathname: '/overview' }} />
}
and return your login ui if not authenticated as you have
return (
<divclassName="Login"><ButtononClick={handleLogin}>Login</Button></div>
);
Solution 3:
If you want that to login user please Also look into privateRoute which help you secure your page
Please look this tutorial for more details react auth tutorial click here
Post a Comment for "Redirect To Route Within Function React Router Dom"