Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset ReactJS file input

I have file upload input:

<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/> 

And I handle upload this way:

getFile(e) {     e.preventDefault();     let reader = new FileReader();     let file = e.target.files[0];     reader.onloadend = (theFile) => {         var data = {             blob: theFile.target.result, name: file.name,             visitorId:  this.props.socketio.visitorId         };         console.log(this.props.socketio);         this.props.socketio.emit('file-upload', data);     };     reader.readAsDataURL(file); } 

If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?

like image 373
Stepan Yakovenko Avatar asked Feb 12 '17 19:02

Stepan Yakovenko


People also ask

How do you reset all input field in React?

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).

How do I change the input value of a file?

The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.

How do I give a value to an input type file in React?

To hold file input's value in React, we can store the selected file in a state. We create the file state with the useState hook. Then we add the handleChange function that gets the selected file from the e.


1 Answers

I think you can just clear the input value like this :

e.target.value = null; 

File input cannot be controlled, there is no React specific way to do that.


Edit For old browsers (<IE11), you can use one of the following techniques.

See http://jsbin.com/zurudemuma/1/edit?js,output (tested on IE10 & 9)

like image 83
Freez Avatar answered Oct 01 '22 07:10

Freez