Iteration over FileList, React, Typescript
The FileList
interface is accessed using the index:
for (let i = 0; i < files.length; i++) {
console.log(files[i].name);
//or
console.log(files.item(i).name);
}
You can use either the index with [0]
or via item(0)
.
FileList is an Array like object, that has the length
property, and indexed values, but it lacks the Array methods, such as map. With ES6 you can use spread or Array#from to convert it to a real array. In ES5 you can call Array#slice to convert to an array, or call the method on the FileList.
Note: If Array#from causes the TypeScript | Array.from | error TS2339: Property 'from' does not exist on type 'ArrayConstructor' error, change the default target (es3) to ES6 - "target": "ES6"
- in the compiler options of the "tsconfig.json", or use the --target ES6 in the command line.
Array.from demo:
const onInputChanged = (e) => {
const files = e.currentTarget.files;
Array.from(files).forEach(file => console.log("Do something with " + file.name));
}
<input
type="file"
onChange="onInputChanged(event)"
/>
Calling forEach demo:
const onInputChanged = (e) => {
const files = e.currentTarget.files;
[].forEach.call(files, file => console.log("Do something with " + file.name));
}
<input
type="file"
onChange="onInputChanged(event)"
/>