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.
To redirect on form submit using React Router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it the path - navigate('/contacts') . The navigate() function lets us navigate programmatically.
We can redirect programmatically in the component itself or a middleware. In this guide, we are going to learn how to redirect when there's a successful async action. There are several ways to redirect a user to another route, including the history. push() method and the <Redirect /> component from react-router .
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 (
...
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With