Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use FieldArray alongside useFormik hook?

Tags:

reactjs

formik

In my form component, I want to use FieldArray with useFormik hook. When I try to do that I get TypeError: _this$props2$formik is undefined error.

Should I switch to class component or can I somehow inject formik to FieldArray? Or is there a way to do that?

const MyForm = ({openPanel}) => {
    const intl = useIntl();

    const formData = useSelector(state => state.form[Forms.SOURCE_EDIT]);

    const formik = useFormik({
        initialValues: {
            style: formData ? formData.style : '',
            layers: formData ? formData.layers : [],
        },
        validationSchema: createValidationSchema(),
        onSubmit: async values => {
            // ...
        },
    });

    const {
        values,
        errors,
        touched,
        handleSubmit,
        isSubmitting,
        handleChange,
        handleBlur,
    } = formik;

    return (
        <div className={'center-flex'}>
            <form onSubmit={handleSubmit}>
                {/* ... */}
                <FieldArray
                    name={'layers'}
                    render={arrayHelpers => (
                        <div>
                            {values.layers.map((layer, index) => (
                                <div key={index}>{layer.name}</div>
                            ))}
                        </div>
                    )}
                />
                <Button
                    large
                    intent={Intent.PRIMARY}
                    fill
                    loading={isSubmitting}
                    disabled={isSubmitting}
                    type={'submit'}>
                    {intl.formatMessage(messages.next)}
                </Button>
            </form>
        </div>
    );
};

Thanks in advance

like image 272
kursat Avatar asked Nov 27 '22 02:11

kursat


1 Answers

Probably a bit late, but you can use FormikProvider which takes useFormik value as a prop.

const formik = useFormik()
....
<FormikProvider value={formik}>
  <FieldArray name="" render={() => (...) />
</FormikProvider>
like image 150
net-junkie Avatar answered Dec 05 '22 05:12

net-junkie