0

I've started with learning React JS and my problem is that; I want to select multiple file from file dialog and then I want to display them on the screen with their name.

<RaisedButton className="raisedBtn" label="Video Ekle" onClick={this.openFileDialog}>
           <input
             ref={(input) => { this.textInput = input; }}
             style={{"display" : "none"}}
             type="file" multiple   
             onChange={this.handleFileChange}
             >
           </input>
         </RaisedButton>

There is okay.

openFileDialog(){ ReactDOM.findDOMNode(this.textInput).click(); }

There is okay again.

The problem is there:

handleFileChange(e){
var files = e.target.files;

for (var i = 0; i < files.length; i++) {
  var file = files[i];
  let reader = new FileReader();
  var fileName = file.name;

  reader.onload = (e) => {
      tilesData.push({img: e.target.result, title: fileName})
      this.setState({image: e.target.result,  title: fileName});

 };

reader.readAsDataURL(file);

   }
}

All images name are the same (all of them have the last selected file's name). I think reader.onload is running asynchronous so the for loop go on but reader.onload is not finish the running? How can I fix it?

Thanks in your advance.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Selin Gök
  • 331
  • 1
  • 5
  • 20
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Mayank Shukla Aug 18 '17 at 13:09
  • it's related to very interesting topic of js "Closures", use `let` instead of `var` here, it should work: `let fileName = file.name;` Check the [**link**](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable) for diff between these two. – Mayank Shukla Aug 18 '17 at 13:16
  • 1
    @MayankShukla thanks it works. "The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block. Also, variables declared with let are not accessible before they are declared in their enclosing block" – Selin Gök Aug 18 '17 at 13:18

0 Answers0