HendPro12
HendPro12

Reputation: 1104

Dynamic Formik Form Using withFormik

I am trying to create a React Component which will return a Formik Form that uses withFormik. This component will get passed another Component as a prop which returns the content of the form. Is this possible? I can't identify how to pass custom props to mapPropsToValues (basically how to put something custom in the place of :

   one:'',
   two:'',
   three:''

in the code below:

const DynamicCustomForm = ({FormType, formName, formFields,  ...props}) => {

    console.log(props);

        const {
            values,
            touched,
            errors,
            status,
            handleChange,
            handleBlur,
            setFieldValue,
            setFieldTouched,
            validateField,
            validateForm,
            handleSubmit,
            isSubmitting,
        } = props;
        return (
            <form onSubmit={handleSubmit}>
                <Field name={formName} >
                    {({
                        field,
                        form,
                        meta,
                    }) => (
                        <FormType />
                    )}
                </Field>

                <Button type="submit" className="button" disabled={isSubmitting}>
                    Submit
                </Button>

            </form>

        );
    };


    const FormikEnhancedDynamicCustomForm = withFormik({
        mapPropsToValues: () => ({
            one:'',
            two:'',
            three:''
        }),
        validateOnMount: false,
        validateOnBlur: false,
        //validate: validate,
        handleSubmit: (values, { setSubmitting }) => {
            handleSubmit(values);
            setTimeout(() => {
                alert(JSON.stringify(values, null, 2));
                setSubmitting(false);
            }, 1000);
        },

        displayName: 'DynamicCustomForm',
    })(DynamicCustomForm);

    export default FormikEnhancedDynamicCustomForm;

Upvotes: 0

Views: 934

Answers (1)

HendPro12
HendPro12

Reputation: 1104

This post https://github.com/jaredpalmer/formik/issues/752 helped me to identify that if I remove mapPropsToValues then anything I pass as a prop to the Component with the Formik form will get added as Formik values. I'd still be interested if there are other ways of accomplishing this.

Upvotes: 1

Related Questions