Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React+redux-form - redirect after submit

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.

like image 573
Mateusz Avatar asked Apr 29 '17 17:04

Mateusz


People also ask

How do I redirect a form after submission in react?

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.

Can I redirect from Redux action?

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 .


1 Answers

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 (
     ...
   )  

  }
}
like image 106
mrinalmech Avatar answered Sep 24 '22 13:09

mrinalmech