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()`
@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