I am using react-router-dom v4 . How can I redirect to the page after form submit success?
I followed that tutorial LINK . Then I created my own submit function :
const submit=({email='',password=''})=>{
let error={};
let isError=false;
if(email.trim()===''){
error.email='Required';
isError=true;
}
else if(![ '[email protected]' ].includes(email)){
error.email='User does not exist';
isError=true;
}
if(password.trim()===''){
error.password='Required';
isError=true;
}
else if(password!=='test'){
error.password='Wrong password';
isError=true;
}
if(isError){
throw new SubmissionError(error);
}
else{
//redirect to new page
}
}
In the comment place there should be a redirect funtion, but I don't have idea how to do it. I tried put there :
<Redirect to="/pageAfterSubmit" push />
but nothing happened.
My browser router in index.js looks like this:
<BrowserRouter >
<Provider store={store}>
<div>
<Route path="/" component={LoginForm}></Route>
<Route path="/markers" component={Markers}></Route>
<Route path="/contact" component={Contact}></Route>
</div>
</Provider >
</BrowserRouter>
Thanks for any help.
Create a state variable redirectToNewPage
which when true does the redirect. In the callback
set redirectToNewPage
equal to true.
class LoginForm extends React.Component {
state = {
redirectToNewPage: false
}
const submit=({email='',password=''})=>{
...
else{
//redirect to new page
this.setState({ redirectToNewPage: true })
}
}
render() {
// The part that makes the redirect happen
if (this.state.redirectToNewPage) {
return (
<Redirect to="/pageAfterSubmit"/>
)
}
return (
...
)
}
}