DDavis25
DDavis25

Reputation: 1319

How do I add each item from my for loop onto my array ReactJS

I'm trying to allow users to select mp3 tracks from a directory and have it display in a playlist on the screen. So far I'm using a for loop to grab each of the files but I'm not sure how I would iterate through the files and create a new {name: file.name} for each file and add it to files: []. Right now only the last element from the for loop is displaying through my .map() function in my li when I want all the selected files to display. Here's my code:

class Download extends React.Component {

    constructor(props) {
     super(props)

     this.handleClick = this.handleClick.bind(this);

     this.inputRef = React.createRef();



     this.state = {
        files: [],
     }




}


   handleClick = () => {

    const node = this.inputRef.current;

    var self = this;

    var file;

    var name;


node.addEventListener('change', function() {


for(var x = 0, xlen = this.files.length; x < xlen; x++) {

  file = this.files[x];

  name = file.name;

  console.log(name);

  //append {name: 'file.name'} x amount of times to files: [] //

}

 self.setState({ files: [{ name: name }] });


});

};






render() {
return(

<div className="input">
<input onClick={this.handleClick} id="upload-file" className="inputName" type="file" multiple ref={this.inputRef}/>
<div>
 <ul ref={this.ulRef}>
   {this.state.files.map((file, index) => (
          <li key={index}>
            {file.name}
          </li>
        ))}
</ul>
</div>
<output id="list"></output>



</div>

)


};



}





    export default Download;

Upvotes: 0

Views: 53

Answers (1)

TKoL
TKoL

Reputation: 13932

try this instead:

const fileList = [];

for(var x = 0, xlen = this.files.length; x < xlen; x++) {
  file = this.files[x];
  name = file.name;
  console.log(name);
  fileList.push({name:name});
  //append {name: 'file.name'} x amount of times to files: [] //
}

 self.setState({ files: fileList });

Upvotes: 1

Related Questions