Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created May 12, 2019 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/45698ab446b16ec445647db97a6cd5c0 to your computer and use it in GitHub Desktop.
Save alfonmga/45698ab446b16ec445647db97a6cd5c0 to your computer and use it in GitHub Desktop.
Example enhanced form with Formik
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