Search code examples
reactjsfilelist

React Loop Through FileList and Display


I am trying to loop through a FileList in React and not having any luck.

enter image description here

I have read this article on Can't use forEach with Filelist and with it's help I am able to print to the console. And this Loop inside React JSX article to help with the loop part however I am not able to display any results.

renderEligibilityDocs(e) {
var proctorDocChanges = this.state.proctorDocChanges;
var files = proctorDocChanges[313];
console.log("files", files);
if (files) {
  var post = Array.from(files).forEach(file => {
    return (
      <div key={file.name}>
        <h2>file: {file.name}</h2>
      </div>
    );
  });

  Array.from(files).forEach(file => console.log("Print to Console " + file.name));
  return <div>
    {post}
  </div>;

} else {
  return <div>
    <span>No Files Uploaded</span>
  </div>;
}

}

What is the concept that I am missing to display the files in the H tag?


Solution

  • If you want to capture or render the output you should use map instead of forEach.

    forEach executes a function for each element but it doesn't do anything with the return values, whereas map builds an array from them.

    if (files) {
      return Array.from(files).map(file => {
        return (
          <div key={file.name}>
            <h2>file: {file.name}</h2>
          </div>
        );
      });
    }
    else {
      ...
    }