How to reset ReactJS file input

What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:

functionThatResetsTheFileInput() {
  let randomString = Math.random().toString(36);

  this.setState({
    theInputKey: randomString
  });
}

render() {
  return(
    <div>
      <input type="file"
             key={this.state.theInputKey || '' } />
      <button onClick={this.functionThatResetsTheFileInput()} />
    </div>
  )
}

That forces React to render the input again from scratch.


This work for me - ref={ref => this.fileInput = ref}

<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />

then in my case once the file was uploaded to the server , I clear it by using the statement below

 this.fileInput.value = "";

I do it by updating key inside my file input. This will force a re-render and previously selected file will go away.

<input type="file" key={this.state.inputKey} />

Changing the state inputKey will re-render the component. One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.


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)