0

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?

2 Answers 2

3

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

Comments

1

The forEach method doesn't return anything. This is fine for your second loop where you just want to do a console.log, but your first loop needs to return something - you should use map there.

You can also move the map statement into the return statement:

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

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.