How to Reset a File input in React
In this post we will give you information about How to Reset a File input in React. Hear we will give you detail about How to Reset a File input in ReactAnd how to use it also give you demo for it if it is necessary.
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.
Hope this code and post will helped you for implement How to Reset a File input in React. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs