Skip to content

Instantly share code, notes, and snippets.

@elitan
Last active November 9, 2022 05:21
Show Gist options
  • Save elitan/5e4cab413dc201e0598ee05287ee4338 to your computer and use it in GitHub Desktop.
Save elitan/5e4cab413dc201e0598ee05287ee4338 to your computer and use it in GitHub Desktop.
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()`
@cheresioana
Copy link

It worked instantly. Thank you!

@teneeto
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
Copy link

worked!! thanks

@okabamac
Copy link

Thanks alot, still very useful!

@ryanwevans
Copy link

Worked immediately, thank you!

@deehusky
Copy link

THANK YOU!!!!

@Code-God007
Copy link

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
Copy link

Thank you so much!!!

@andrefcordeiro
Copy link

Thank you !!!!

@itsamirkhan
Copy link

Thank You Friend

@arnel-hernandez
Copy link

Thank you!!!!

@joshamore
Copy link

Thank you!

@ashraf-hussain-mazumder
Copy link

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

@ArunTeltia
Copy link

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

@mark081
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
Copy link

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

@tanyamehta
Copy link

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
Copy link

@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
Copy link

Thanks a lot .You made my day

@s0m0c12
Copy link

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
Copy link

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

@manoelblue
Copy link

OMG, thank you so much!

@NegativeDivinity
Copy link

Thank you so much!

@nidhidsharma08121988
Copy link

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
Copy link

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
Copy link

kayalvizhiulagu commented Jun 18, 2021

Its working..Thank you

@juanccamachob94
Copy link

It works! I love you!

@elitan
Copy link
Author

elitan commented Jun 23, 2021

It works! I love you!

❤️

@nicolassso
Copy link

Thanks a lot!

@luizhcordeiro
Copy link

Thanks

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