Created
January 19, 2018 10:35
-
-
Save JoaoCnh/061c267382572ce2b359222816b7f9b8 to your computer and use it in GitHub Desktop.
Submitting forms with React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Formik, Form, Field } from "formik"; | |
import yup from "yup"; | |
class Form extends React.Component { | |
state = { error: false }; | |
_submit = async (values, { setSubmitting }) => { | |
// build form data | |
const formData = new FormData(); | |
formData.append("email", values.email); | |
formData.append("name", values.name); | |
try { | |
const res = await fetch("/api/url", { method: "POST", body: formData }); | |
const json = res.json(); | |
setSubmitting(false); | |
// redirect or do something else. | |
} catch (error) { | |
setSubmitting(false); | |
this.setState({ error: error.message }); | |
} | |
}; | |
render() { | |
return ( | |
<div> | |
{this.state.error && ( | |
<div className="alert alert-danger"> | |
<h3>Oops...</h3> | |
<pre>{this.state.error.message}</pre> | |
</div> | |
)} | |
<Formik | |
initialValues={{ | |
name: "", | |
email: "", | |
}} | |
validationSchema={yup.object().shape({ | |
name: yup.string().required(), | |
email: yup.string().email().required(), | |
})} | |
onSubmit={this._submit} | |
render={({ isSubmitting }) => ( | |
<Form> | |
<div className="form-group"> | |
<label htmlFor="name">Name</label> | |
<Field type="text" name="name" className="form-control" /> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="email">E-mail</label> | |
<Field type="email" name="email" className="form-control" /> | |
</div> | |
<button type="submit" disabled={isSubmitting}> | |
Submit | |
</button> | |
</Form> | |
)} /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment