Borislav Hadzhiev
Sat Apr 16 2022·2 min read
Photo by Jéssica Oliveira
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 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;
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
.
Alternatively, 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.