Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  4] [ 4]  / answers: 1 / hits: 5226  / 3 Years ago, tue, april 6, 2021, 12:00:00

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.


More From » html

 Answers
9

You can use the useRef to get reference to the file input and clear it like this.


import { Formik, Field } from "formik";
import { useRef } from "react";

export default function App() {
const fileRef = useRef();

return (
<div className="App">
<Formik
initialValues={{ files: null }}
onSubmit={console.log}
>
{({ setFieldValue, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field
innerRef={fileRef}
name="files"
type="file"
multiple
/>
<button type="submit">Submit</button>
</form>
)}
</Formik>
<button onClick={() => (fileRef.current.value = null)}>Clear</button>
</div>
);
}


[#1526] Wednesday, March 31, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;