Formik resetForm() does not reset the entire form when there is a custom component

Viewed 8602

I'm using Formik - and formik-material-ui - to handle my forms. In one of these forms, I include a CustomFileUpload component:

import React from "react";

import {
    Input,
    FormControl,
} from "@material-ui/core";

const CustomFileUpload = (props) => (
    <FormControl>
        <Input
            inputProps={{
                type: "file",
                disabled: props.disabled || props.form.isSubmitting,
                name: props.field.name,
                onChange: (event) => {
                    const file = event.currentTarget.files[0];
                    props.form.setFieldValue(props.field.name, file);
                },
            }}
        />
    </FormControl>
);

export default CustomFileUpload;

Despite its value being read by my form, and reachable through the following testSubmit function, the field handled by my CustomFileUpload component field is the only one not being reset when calling the function resetForm:

const testSubmit = (values, { resetForm }) => {
    console.log(values);
    resetForm();
};

In case it might be useful, when removing all the "working fields", this is what my Formik component looks like:

<Formik
    initialValues={{
        cover: cover
    }}
    onSubmit={(values, { setSubmitting, resetForm }) => {
        testSubmit(values, { resetForm });
    }}
>
    {({ submitForm, isSubmitting }) => (
        <div className="flex">
            <Form>
                <Field
                    component={CustomFileUpload}
                    label="Cover image"
                    name="cover"
                />

                <Button
                    onClick={submitForm}
                >
                    Submit
                </Button>
            </Form>
        </div>
    )}
</Formik>

Does someone know why the cover value is reachable through console.log(values) but not being reset by resetForm()?

2 Answers

I had already faced this issue. Have you try to pass the values to exact the input.

{({ submitForm, isSubmitting, values }) => (
    <div className="flex">
        <Form>
            <Field
                component={CustomFileUpload}
                label="Cover image"
                name="cover"
                value = { values.cover || "" } <-- insert this
            />

You need to give your Field a value property... try this

<Field
  component={CustomFileUpload}
  label="Cover image"
  name="cover"
  value={values.cover}
/>
Related