There is input
with type='file'
attribute like this:
function TestComp() {
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const [file] = e.target.files;
//...
};
return <input type='file' onChange={onChange}/>
}
Got error:
type 'FileList | null' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)
The e.target.files
TS type is:
interface HTMLInputElement extends HTMLElement {
/**
* Returns a FileList object on a file type input object.
*/
files: FileList | null;
}
In what scenario, the e.target.files
may be null
?
CodePudding user response:
That's the behaviour of HTMLFileElement
, it returns null
for files
if the type
is not set to file
.
const fileInput = document.createElement('input');
fileInput.files // null
fileInput.type = "file"
fileInput.files // FileList
CodePudding user response:
I have tried to work around with this a bit different way and it works
import React from 'react';
interface Event<T = EventTarget> {
target: T;
}
export default function FileUploadPage() {
const changeHandler = (event: React.ChangeEvent<HTMLInputElement>): void => {
const target = event.target as HTMLInputElement;
const files = target.files;
console.log(files)
};
const handleSubmission = () => {
};
return (
<div>
<input type="file" name="file" multiple onChange={changeHandler} />
<div>
<button onClick={handleSubmission}>Submit</button>
</div>
</div>
)
}