Most <input>
elements use a value
prop to set the value, and so they can be externally controlled by a parent.
However <input type='file'>
sets its value from a files
attribute, and I'm struggling to make that work correctly. files
can not be set directly as a prop, but it can be set on the DOM directly via a ref, so I use useEffect()
to accomplish this:
import React, { useEffect, useRef } from "react";
const FileInput = (props) => {
const { value } = props;
const inputRef = useRef();
useEffect(() => {
if (value === "") {
inputRef.current.value = "";
} else {
inputRef.current.files = value;
}
}, [value]);
return <input type="file" ref={inputRef} />;
};
export default FileInput;
I'd like to include an onChange()
handler for when the user selects a file, but the <FileList>
object is tied to the DOM and I get an error when trying to use it to set the value
:
DOMException: An attempt was made to use an object that is not, or is no longer, usable
I keep going in circles on the "right" way to write a controlled form input. Is there a way to set the files
attribute and value
attribute correctly?
Thanks!