Reset a File input in React

avatar

Borislav Hadzhiev

Last updated: Apr 16, 2022

banner

Photo from Unsplash

Reset a File input in React #

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.

App.js
const App = () => { const handleFileChange = event => { const fileObj = event.target.files && event.target.files[0]; if (!fileObj) { return; } console.log('fileObj is', fileObj); // 👇️ reset file input event.target.value = null; // 👇️ is now empty console.log(event.target.files); // 👇️ can still access file object here console.log(fileObj); console.log(fileObj.name); }; return ( <div> <input type="file" onChange={handleFileChange} /> </div> ); }; export default App;

reset file input

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.

Note that we stored the file object in a variable, so we have access to it even after the file input's value is reset.

Alternatively, you can assign a ref to the file input, which would allow you to reset its value from anywhere.

App.js
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.

Notice that we have to access the 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.

Note that you are able to reset the file input's value from anywhere now, because we have access to the input field from anywhere via the ref.

The current property on the inputRef object refers to the file input.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.