How to Reset a File input in React
In this tutorial, we are going to learn about How to Reset a File input in React with the help of an example.
Resetting a File input in React
To reset a file input in React, we can set the event.target.value = null to the input element’s event object. By setting the input element’s target.value
property to null
resets the file input.
Here is an example:
import React from 'react';
const App = () => {
const handleFileChange = (event) => {
// resetting the file input
event.target.value = null;
};
return (
<div>
<input type="file" onChange={handleFileChange} />
</div>
);
};
export default App;
In the example above, we have added the event.target.value = null
to the handleChange function, so whenever a data is changed in the input element it resets the file.
Resetting the file input by Button click
To reset a file input by clicking the button:
-
Access the input element dom object using the useRef() hook.
-
Add the inputRef.current.value = null to the button click event handler function, so whenever a user click the reset button resets the input file.
import {useRef} from 'react';
const App = () => {
// creating the ref for file input
const inputRef = useRef(null);
const resetFileInput = () => {
// resetting the input value
inputRef.current.value = null;
};
return (
<div>
<input ref={inputRef} type="file" />
<button onClick={resetFileInput}>Reset file</button>
</div>
);
};
The useRef() hook returns a mutable refernce object of the passed element, whose .current
property is initialized to the passed argument as initialValue.