0

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;

1 Answer 1

1

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 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.