Skip to content

Instantly share code, notes, and snippets.

@slightlytyler
Last active June 27, 2018 18:25
Show Gist options
  • Save slightlytyler/d8cf7d935faed78089d42227002f63dc to your computer and use it in GitHub Desktop.
Save slightlytyler/d8cf7d935faed78089d42227002f63dc to your computer and use it in GitHub Desktop.
withForm HOC that wraps withFormik and includes the event in handleSubmit
// @flow
import { withFormik } from 'formik';
import { compose, pick } from 'lodash/fp';
import PropTypes from 'prop-types';
import { withContext, withHandlers } from 'recompose';
type Config = Object;
const pickFormikBag = pick([
'values',
'errors',
'touched',
'isSubmitting',
'submitCount',
'resetForm',
'submitForm',
'validateForm',
'setError',
'setErrors',
'setFieldError',
'setFieldTouched',
'setFieldValue',
'setStatus',
'setSubmitting',
'setTouched',
'setValues',
'setFormikState',
'dirty',
'isValid',
'initialValues',
'registerField',
'unregisterField',
'handleBlur',
'handleChange',
'handleReset',
'handleSubmit',
'validateOnChange',
'validateOnBlue',
]);
const withForm = (config: Config) => {
const HOC = compose(
withFormik(config),
withHandlers({
handleSubmit: props => e => {
e.preventDefault();
return config.handleSubmit(
props.values,
{ props, ...pickFormikBag(props) },
e
);
},
}),
withContext(
{
formik: PropTypes.object,
},
props => ({
formik: pickFormikBag(props),
})
)
);
return HOC;
};
export default withForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment