Search code examples
reactjsfilefileapi

Select multiple files in react with refs


i am trying to select multiple files with react but my attempts failed i want user to be able to select multiple files to upload next but my code can get only one file when i try to add second file, old file is replaced by new one

i have tried to add multiple attribute to my input element and also accept="image/* but non of them worked. currently i keep trying with multiple. here is my current code

...

  handleFile(e){
        let images = this.imgRef.current.files
        console.log(Array.from(images))
}

...

 <input type="file" name="images" id="imgid" className="imgcls" ref={this.imgRef} onChange={this.handleFile} style={{ display: "none" }} multiple/>

i want to log every file info but this is what i get instead

https://i.sstatic.net/zxJs6.jpg


Solution

  • You don't need refs to access files. You can do it simple from the event received on change, like this:

    class App extends Component {
      handleFile(e) {
        console.log(e.target.files)
      }
    
      render() {
        return (
          <div className="App">
            <input type="file" name="images" id="imgid" className="imgcls" onChange={this.handleFile} multiple/>
          </div>
        );
      }
    }