In my input component I extract file content after input. Took code from here
Error occurred on the line of onChange={e => handleFileChosen(e.target.files[0])}
, to be more accurate, ts underlines e.target.files
.
Error message is 'e.target.files' is possibly 'null'
And here is the code:
import styles from './Input.module.scss'
import { FileInputProps } from './FileInput.props';
import cn from 'classnames'
import { useState } from 'react';
export const FileInput = ({ ...props }: FileInputProps): JSX.Element => {
const [fileContent, setFileContent] = useState<string>('')
const handleFileChosen = (file: File) => {
let fileReader = new FileReader()
fileReader.onloadend = (e: Event) => {
const content = fileReader.result || ''
setFileContent(content.toString())
}
fileReader.readAsText(file)
}
return (
<>
<input
type='file'
onChange={(e) => {handleFileChosen(e.target.files[0])}}
/>
<p>{fileContent}</p>
</>
)
}
I've checked this SO page, but none of those solutions helped me
import React, {ChangeEvent, useEffect, useState} from 'react';
const FileUploadComponent = () => {
const [base64Data, setBase64Data] = useState("");
const [error, setError] = useState("");
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const files: FileList | null = e.target.files;
const reader: FileReader = new FileReader();
reader.onloadend = function () {
setBase64Data(reader.result as string)
}
reader.onerror = function () {
setError("Error file not reading");
}
reader.readAsDataURL(files?.[0] as File);
}
useEffect(()=> {
console.log(base64Data)
}, [base64Data])
return (
<div>
<input
className={"form-control"}
type={"file"}
onChange={handleFileChange}
/>
</div>
);
};
export default FileUploadComponent;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.