Skip to content

Instantly share code, notes, and snippets.

@verticalgrain
Last active April 26, 2022 15:37
Show Gist options
  • Save verticalgrain/195468e69f2ac88f3d9573d285b09764 to your computer and use it in GitHub Desktop.
Save verticalgrain/195468e69f2ac88f3d9573d285b09764 to your computer and use it in GitHub Desktop.
React Router V4 Redirect after form submission
import React, { Component } from 'react'
import { Redirect } from 'react-router'
export default class ContactForm extends Component {
constructor () {
super();
this.state = {
fireRedirect: false
}
}
submitForm = (e) => {
e.preventDefault()
this.setState({ fireRedirect: true })
}
render () {
const { from } = this.props.location.state || '/'
const { fireRedirect } = this.state
return (
<div>
<form onSubmit={this.submitForm}>
<button type="submit">Submit</button>
</form>
{fireRedirect && (
<Redirect to={from || '/thank-you'}/>
)}
</div>
)
}
}
@lucasalberto
Copy link

Thanks! Very clean solution!

@ggf-84
Copy link

ggf-84 commented May 12, 2019

Thank you!!!!

@irfanonk
Copy link

irfanonk commented Apr 23, 2020

I think this is another solution. Since there are there elemnet that router provides which are match, location adn history, we may push any route to history. considering rerouting after submiting a form:
{history} = this.props <button onClick={this.onFormSubmit(formValues, history)} )> Submit <button/> ( onFormSubmit(formValues, history) { database.post(formValues) (some codes) history.push('/') } )

@IvoTsochev
Copy link

nice one

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