Sometimes, we want to reset a file input’s value in React.
In this article, we’ll look at how to reset a file input’s value in React.
Reset a File Input’s Value in React
To reset a file input’s value in React, we can set the value
property of the file input to an empty string.
For instance, we can write:
import React, { useRef } from "react";
export default function App() {
const ref = useRef();
const reset = () => {
ref.current.value = "";
};
return (
<>
<input type="file" ref={ref} />
<button onClick={reset}>reset</button>
</>
);
}
We call the useRef
hook to create a ref object.
And we assign that to the file input with the ref
prop.
Next, we add a button that calls the reset
function when we click it.
And in the reset
function, we set ref.current.value
to an empty string.
ref.current
is the file input element since we passed ref
to the ref
prop.
Conclusion
To reset a file input’s value in React, we can set the value
property of the file input to an empty string.
2 replies on “How to Reset a File Input’s Value in React?”
This approach doesn’t work. Even if current.value is set to an empty string, the actual contents of the input type file are stored in current.files; The current.files return a File object which itself is immutable. I’m currently trying to find a way to actually remove this file from current.files, so if you have any tips I’d be very grateful.
The code just clears the file input display. You should keep track of the files in its own state instead of relying on the files property.