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 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 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 sharifme04 commented Feb 8, 2018

great solution. now I can sleep properly after this

@willardshikami

This comment has been minimized.

Copy link

@willardshikami willardshikami commented Jun 9, 2018

Thank you so much

@dorisobor

This comment has been minimized.

Copy link

@dorisobor dorisobor commented Jun 12, 2018

Thank you, this helped alot!

@SureshPoobal

This comment has been minimized.

Copy link

@SureshPoobal 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 gmiguel14 commented Sep 12, 2018

Thanks!

@lauragift21

This comment has been minimized.

Copy link

@lauragift21 lauragift21 commented Nov 2, 2018

Thanks this helped!

@cheresioana

This comment has been minimized.

Copy link

@cheresioana cheresioana commented Jan 10, 2019

It worked instantly. Thank you!

@teneeto

This comment has been minimized.

Copy link

@teneeto 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 Israel025 commented Mar 22, 2019

worked!! thanks

@okabamac

This comment has been minimized.

Copy link

@okabamac okabamac commented May 22, 2019

Thanks alot, still very useful!

@ryanwevans

This comment has been minimized.

Copy link

@ryanwevans ryanwevans commented Jul 25, 2019

Worked immediately, thank you!

@deehusky

This comment has been minimized.

Copy link

@deehusky deehusky commented Aug 27, 2019

THANK YOU!!!!

@Code-God007

This comment has been minimized.

Copy link

@Code-God007 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 huyhoang1001 commented Nov 19, 2019

Thank you so much!!!

@andrefcordeiro

This comment has been minimized.

Copy link

@andrefcordeiro andrefcordeiro commented Jan 31, 2020

Thank you !!!!

@itsamirkhan

This comment has been minimized.

Copy link

@itsamirkhan itsamirkhan commented Feb 1, 2020

Thank You Friend

@arnel-hernandez

This comment has been minimized.

Copy link

@arnel-hernandez arnel-hernandez commented Mar 23, 2020

Thank you!!!!

@joshamore

This comment has been minimized.

Copy link

@joshamore joshamore commented Apr 26, 2020

Thank you!

@ashraf-hussain-mazumder

This comment has been minimized.

Copy link

@ashraf-hussain-mazumder 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 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 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 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 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 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 Sampreeth2002 commented Jul 28, 2020

Thanks a lot .You made my day

@s0m0c12

This comment has been minimized.

Copy link

@s0m0c12 s0m0c12 commented Sep 10, 2020

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)));

Did you resolve this issue?

@sohye-lee

This comment has been minimized.

Copy link

@sohye-lee sohye-lee commented Nov 23, 2020

Hi,
after you build a static folder with 'yarn build' or 'npm run build' on your terminal (inside your project folder),
you must make a file named '_redirects' inside 'build' folder.
then inside the '_redirects' folder, you write below:

/* /index.html 200

And go to Netlify and drag and drop your whole 'build' folder into the build site box.
It ran smoothly for me.

I hope this helps somebody.
Screen Shot 2020-11-23 at 15 49 09

@jnhemant

This comment has been minimized.

Copy link

@jnhemant jnhemant commented Jan 8, 2021

Thanks for this!

@ManoelBlue

This comment has been minimized.

Copy link

@ManoelBlue ManoelBlue commented Feb 15, 2021

OMG, thank you so much!

@NegativeDivinity

This comment has been minimized.

Copy link

@NegativeDivinity NegativeDivinity commented Apr 17, 2021

Thank you so much!

@nidhidsharma08121988

This comment has been minimized.

Copy link

@nidhidsharma08121988 nidhidsharma08121988 commented Jun 11, 2021

thank you. :)
I needed this :
this.props.history.push('/thank-you'); // <--- The page you want to redirect your user to.

@voyagebagage

This comment has been minimized.

Copy link

@voyagebagage voyagebagage commented Jun 11, 2021

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)));

the ANSWER: https://www.youtube.com/watch?v=QgpJHN_EOGM
< Route > your app in index.js if you are working in App.js

@kayalvizhiulagu

This comment has been minimized.

Copy link

@kayalvizhiulagu kayalvizhiulagu commented Jun 18, 2021

Its working..Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment