Created
May 12, 2019 20:01
-
-
Save alfonmga/45698ab446b16ec445647db97a6cd5c0 to your computer and use it in GitHub Desktop.
Example enhanced form with Formik
This file contains 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 { withFormik } from 'formik'; | |
const MyForm = props => { | |
const { | |
values, | |
touched, | |
errors, | |
handleChange, | |
handleBlur, | |
handleSubmit, | |
} = props; | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input | |
type="text" | |
onChange={handleChange} | |
onBlur={handleBlur} | |
value={values.name} | |
name="name" | |
/> | |
{errors.name && touched.name && <div id="feedback">{errors.name}</div>} | |
<button type="submit">Submit</button> | |
</form> | |
); | |
}; | |
const MyEnhancedForm = withFormik({ | |
mapPropsToValues: () => ({ name: '' }), | |
// Custom sync validation | |
validate: values => { | |
const errors = {}; | |
if (!values.name) { | |
errors.name = 'Required'; | |
} | |
return errors; | |
}, | |
handleSubmit: (values, { setSubmitting }) => { | |
setTimeout(() => { | |
alert(JSON.stringify(values, null, 2)); | |
setSubmitting(false); | |
}, 1000); | |
}, | |
displayName: 'BasicForm', | |
})(MyForm); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment