'Is there a way to pass data to Formik's HOC (Higher Order Component) withFormik() in React?
I have semi-legacy code. There's some Formik components that are being wrapped with withFormik().
The primary thing is, the variable/data is not part of the initial props of the wrapped component. A possible example is if React Context API is being used. That means it isn't part of the props. Quick simple React component and withFormik() below with React's useContext hook being used in the wrapped component, but would like access to it in the withFormik() HOC.
Also, the data can't be passed through [hidden] fields in the form. I realize that is an easy way to do it and grab it in values. Wondering if there is another way.
import React, { useContext } from 'react';
import { Form, Field, withFormik } from 'formik';
const MyForm = props => {
const { section } = useContext( SectionContext );
return (
<Form>
<Field
component="input"
name="name"
/>
{errors.name && touched.name && <div id="feedback">{errors.name}</div>}
<button type="submit">Submit</button>
</form>
);
};
const MyEnhancedForm = withFormik({
mapPropsToValues: () => ({ name: '' }),
handleSubmit: (values, { setSubmitting, props }) => {
// Want to use the context, section.
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}
})(MyForm);
Thanks for any help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
