I am trying to loop through a FileList in React and not having any luck.
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?
CodePudding user response:
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 {
...
}
CodePudding user response:
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>
)
}