How to allow input type=file to select the same file in react component

I have a react component which renders a <input type="file"> dom to allow user select images from browser. I found that its onChange method not called when I select the same file. After some searching, someone suggests using this.value=null or return false at the end of the onChange method but I have tried it doesn't work.

Below is my code:

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { this.readFile(event) }}/>

Below is what I tried:

<input id="upload" ref="upload" type="file" accept="image/*"
               onChange={(event)=> { 
                   this.readFile(event) 
                   return false
              }}/>

Another one is:

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
               this.value=null
          }}/>

I believe above solutions work for jquery but I don't know how to let it work in reactjs.


Solution 1:

Dup of this thread

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
          }}
        onClick={(event)=> { 
               event.target.value = null
          }}

/>

Solution 2:

I think this in your function does not refer to input field. Try using event.target instead.

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
               event.target.value=null
          }}/>

Solution 3:

For me actually worked: event.currentTarget.value = null

    onClick={(event)=> { 
               event.currentTarget.value = null
          }}

Solution 4:

My React version: 16.2.0

@jbsmoove solution works fine for all browsers except IE11.

As for IE11, in case if we Open some file and in second time we press Cancel insteed of Open file it shows empty screen and in console we see:

Unable to get property 'name' of undefined or null reference

So I've come up with another solution which works perfect even in IE11:

<input id="upload" ref="upload" type="file" accept="image/*"
      onInput={(event)=> { 
           this.readFile(event) 
      }}
      onClick={(event)=> { 
           event.target.value = null
      }}
/>

Just use onInput instead of onChange.