I can't find a proper way of handling a multiple files input using Formik and React.
import { Formik, Field } from "formik";
const MyForm = () => {
const handleOnSubmit = (actions) => {
actions.setFieldValue("files", "");
};
return (
<Formik initialValues={{ files: "" }} onSubmit={handleOnSubmit}>
{({ values, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field
id="files"
name="files"
type="file"
multiple
value={values.files}
onChange={(event) => {
setFieldValue("files", Array.from(event.target.files));
}}
/>
<button type="submit">Submit</button>
</form>
)}
</Formik>
);
};
If you pass value={values.files}
you get an InvalidStateError
:
Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
If you pass value={values.files ? undefined : ""}
works but you get the React warning:
A component is changing an uncontrolled input to be controlled.
If you pass value={undefined}
you don't get to control the input value (for emptying the file selection on form submit).
And if you pass value=""
you don't get the name of the selected file (or the number of select files) when selecting files on the input.
Am I missing something? Thank you.
Check an example at Codesandbox.io.