Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Router V4 Redirect after form submission
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'; // <--- import `withRouter`. We will use this in the bottom of our file.
class ContactForm extends Component {
submitForm (e) {
e.preventDefault()
this.props.history.push('/thank-you'); // <--- The page you want to redirect your user to.
}
render() {
return (
<div>
<form onSubmit={this.submitForm.bind(this)}>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
export default withRouter(ContactForm); // <--- make sure to wrap your component with `withRouter()`
@dorklord23

This comment has been minimized.

Copy link

dorklord23 commented Dec 31, 2017

This is what I've been looking for this past weekend. Thank you!!

@ahummel25

This comment has been minimized.

Copy link

ahummel25 commented Feb 3, 2018

When I try to use this example I keep getting Invariant Violation: You should not use <Route> or withRouter() outside a <Router>.

Code:

import React from 'react';
import ReactDOM, { render } from 'react-dom';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { graphql } from 'react-apollo';
import { withRouter } from 'react-router-dom';
import gql from 'graphql-tag';
import registerQuery from './RegisterQuery';
import s from './Register.css';

let postURL;

class Register extends React.Component {

  constructor() {
    super();
    this.state = {
      schoolName: '',
      userName: '',
      password: ''
    };
    this.onSchoolNameChange = this.onSchoolNameChange.bind(this);
    this.onUserNameChange = this.onUserNameChange.bind(this);
    this.onPasswordChange = this.onPasswordChange.bind(this);
  }

  componentDidMount() {
    postURL = `${global.location.origin}/graphql`;
  }

  onSchoolNameChange(event) {
    this.setState({ schoolName: event.target.value });
  }

  onUserNameChange(event) {
    this.setState({ userName: event.target.value });
  }

  onPasswordChange(event) {
    this.setState({ password: event.target.value });
  }

  handleSubmit(data) {
    e.preventDefault();
    this.props.history.push('/login');
  }

  render() {
    console.log(this.props);
    const { schoolName, userName, password } = this.state;
    const isEnabled = schoolName.length > 0 && userName.length > 0 && password.length > 0;
    return (
      <div className={s.root}>
        <div className={s.container}>
          <h1>{this.props.title}</h1>
          <form onSubmit={this.handleSubmit.bind(this)}>
            <div className={s.formGroup}>
              <label className={s.label} htmlFor="schoolName">
                School Name:
                <input
                  className={s.input}
                  id="schoolName"
                  type="text"
                  name="schoolName"
                  value={this.state.schoolName}
                  onChange={this.onSchoolNameChange}
                  autoFocus // eslint-disable-line jsx-a11y/no-autofocus
                />
              </label>
            </div>
            <div className={s.formGroup}>
              <label className={s.label} htmlFor="userName">
                User Name:
                <input
                  className={s.input}
                  id="userName"
                  type="userName"
                  name="userName"
                  value={this.state.userName}
                  onChange={this.onUserNameChange}
                />
              </label>
            </div>
            <div className={s.formGroup}>
              <label className={s.label} htmlFor="password">
                Password:
                <input
                  className={s.input}
                  id="password"
                  type="password"
                  name="password"
                  value={this.state.password}
                  onChange={this.onPasswordChange}
                />
              </label>
            </div>
            <div className={s.formGroup}>
              <button disabled={!isEnabled} className={s.button} type="submit">
                Submit
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default graphql(registerQuery)(withStyles(s)(withRouter(Register)));

@sharifme04

This comment has been minimized.

Copy link

sharifme04 commented Feb 8, 2018

great solution. now I can sleep properly after this

@willardshikami

This comment has been minimized.

Copy link

willardshikami commented Jun 9, 2018

Thank you so much

@dorisobor

This comment has been minimized.

Copy link

dorisobor commented Jun 12, 2018

Thank you, this helped alot!

@SureshPoobal

This comment has been minimized.

Copy link

SureshPoobal commented Jul 2, 2018

This worked for me

https://www.reddit.com/r/reactjs/comments/5x6kku/how_do_i_post_form_data_and_redirect_to_handler/

`handler = (e) => {
// do some validation
this.refs.myForm.submit();
};

const Form = () => (

<form ref='myForm' action='/other-page.html'>
<input id="foo" type="text">
<input type="Submit" />
</form>

);`

@gmiguel14

This comment has been minimized.

Copy link

gmiguel14 commented Sep 12, 2018

Thanks!

@lauragift21

This comment has been minimized.

Copy link

lauragift21 commented Nov 2, 2018

Thanks this helped!

@cheresioana

This comment has been minimized.

Copy link

cheresioana commented Jan 10, 2019

It worked instantly. Thank you!

@teneeto

This comment has been minimized.

Copy link

teneeto commented Feb 1, 2019

This is the fastest code solution i've gotten, i tried once and it worked once, no complexity at all... Thanks @elitan

@Israel025

This comment has been minimized.

Copy link

Israel025 commented Mar 22, 2019

worked!! thanks

@okabamac

This comment has been minimized.

Copy link

okabamac commented May 22, 2019

Thanks alot, still very useful!

@ryanwevans

This comment has been minimized.

Copy link

ryanwevans commented Jul 25, 2019

Worked immediately, thank you!

@deehusky

This comment has been minimized.

Copy link

deehusky commented Aug 27, 2019

THANK YOU!!!!

@Code-God007

This comment has been minimized.

Copy link

Code-God007 commented Nov 2, 2019

Thank You so much. I was looking for this from 2 days and I finally found it today and it still works in 2019.

@huyhoang1001

This comment has been minimized.

Copy link

huyhoang1001 commented Nov 19, 2019

Thank you so much!!!

@trakinaj

This comment has been minimized.

Copy link

trakinaj commented Jan 31, 2020

Thank you !!!!

@itsamirkhan

This comment has been minimized.

Copy link

itsamirkhan commented Feb 1, 2020

Thank You Friend

@arnel-hernandez

This comment has been minimized.

Copy link

arnel-hernandez commented Mar 23, 2020

Thank you!!!!

@joshamore

This comment has been minimized.

Copy link

joshamore commented Apr 26, 2020

Thank you!

@ashraf-hussain-mazumder

This comment has been minimized.

Copy link

ashraf-hussain-mazumder commented May 7, 2020

For functional component, it will be
props.history.push('/thank-you');

@ArunTeltia

This comment has been minimized.

Copy link

ArunTeltia commented Jun 22, 2020

how to wrap the the contact form when you are using redux and wrapping connect already

@mark081

This comment has been minimized.

Copy link

mark081 commented Jun 23, 2020

@ArunTeltia, withRouter is a decorator and can be chained. I have a third one since I'm using redux forms. It ends up looking like this.

export default withRouter(connect(mapStateToProps, { createTrackAction })(
reduxForm({ form: "trackCreate", validate })(TrackCreate))
);

TrackCreate is my component class. Hope that helps.

@ArunTeltia

This comment has been minimized.

Copy link

ArunTeltia commented Jun 23, 2020

@mark081 well thats something new to me i will try this Thank you for help

@tanyamehta

This comment has been minimized.

Copy link

tanyamehta commented Jul 19, 2020

Hi , I have trying to navigate to other URL but it is not at all working for me. Please help me with this:
I want to navigate to /loginSuccess when email and password is correct.

import React, {useState} from "react";
import {NavLink, Redirect, withRouter} from 'react-router-dom';
import LoginSuccess from './LoginSuccess';

function Login(){
const [contact, setContact] = useState({
password : "",
email: ""
});

const [isLogin, setLogin] = useState(true);

  function handleChange(event) {
    const { name, value } = event.target;

    setContact(prevValue => {
      return {
        ...prevValue,
        [name]: value
      };
    });
  
  }
  function handleSubmit(){
    const getPwd = localStorage.getItem('pwd');
    const getEmail = localStorage.getItem('email');
    var em = document.getElementById("emailId").value;
    
    var pwd = '"'+document.getElementById("pwdId").value+'"';
    
    if (getEmail === em && getPwd === pwd) {
      setLogin(true);
      this.context.router.history.push('/loginSuccess');
    }
    else{
      setLogin(false);
      
    }

  }



  return (
    <div className="container">
    <h2>Signed Up Successfully!!</h2>
      <h1>
       Login
      </h1>
      
      <form onSubmit={handleSubmit}> 
        <input id="emailId" className="form-login"
          onChange={handleChange}
          name="email"
          value={contact.email}
          placeholder="Email"
        />
        <input id="pwdId" className="form-login" type="password"
          onChange={handleChange}
          name="password"
          value={contact.password}
          placeholder="Password"
        />
        {/* <button onClick={handleSubmit}>Login</button> */}
        <input type="submit" value="Login"></input>
      </form>
    </div>
  )    

}

export default withRouter(Login);

@ArunTeltia

This comment has been minimized.

Copy link

ArunTeltia commented Jul 20, 2020

@tanyamehta
are you having a router define for the loginsuccess in the main app
if you dont have it may now work
just add a route in the main component for my case its app component

<Route path="/loginsuccess" component={abc123}/>

I also face the problem some time ago and this resolve the issue for me
Try this

@Sampreeth2002

This comment has been minimized.

Copy link

Sampreeth2002 commented Jul 28, 2020

Thanks a lot .You made my day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.