Last updated: Apr 6, 2024
Reading timeยท2 min

To reset a file input in React, set the input's value to null in your
handleChange function, e.g. event.target.value = null.
Setting the element's value property to null resets the file input.
const App = () => { const handleFileChange = event => { const fileObj = event.target.files && event.target.files[0]; if (!fileObj) { return; } console.log('fileObj is', fileObj); // ๐๏ธ reset the file input event.target.value = null; // ๐๏ธ is now empty console.log(event.target.files); // ๐๏ธ can still access the file object here console.log(fileObj); console.log(fileObj.name); }; return ( <div> <input type="file" onChange={handleFileChange} /> </div> ); }; export default App;

The target property on the event object is a reference to the file input
field.
We can reset the file input's value by setting it to null.
I've also written a detailed guide on how to open a file input box on button click.
refAlternatively, you can assign a ref to the file input, which would allow you to reset its value from anywhere.
import {useRef} from 'react'; const App = () => { // ๐๏ธ create a ref for the file input const inputRef = useRef(null); const handleFileChange = event => { const fileObj = event.target.files && event.target.files[0]; if (!fileObj) { return; } console.log('fileObj is', fileObj); }; const resetFileInput = () => { // ๐๏ธ reset input value inputRef.current.value = null; }; return ( <div> <input ref={inputRef} type="file" onChange={handleFileChange} /> <button onClick={resetFileInput}>Reset file input</button> </div> ); }; export default App;

The useRef() hook can be passed an
initial value as an argument. The hook returns a mutable ref object whose
.current property is initialized to the passed argument.
current property on the ref object to get access to the file input element on which we set the ref prop.When we pass a ref prop to an element, e.g. <input ref={myRef} />, React sets
the .current property of the ref object to the corresponding DOM node.
Now every time the button is clicked, the file input's value is reset.
The current property on the inputRef object refers to the file input.