I am trying to preview the image file before uploading.
const [selectedFile, setSelectedFile] = useState<File>();
const [preview, setPreview] = useState<string>();
<form action="" onSubmit={onUploadImage}>
<input
name="file"
type="file"
accept="image/*"
onChange={(event: ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) return
setSelectedFile(event.target.files[0]);
setPreview(URL.createObjectURL(event.target.files[0]));
}} />
<img src={preview} alt="preview" />
</form>
This code above is working.
My problem I would like to solve is finding better way to preview the image file.
As my code, I set selectedFile
as type of File like useState<File>();
It was not allowed to set selectedFile
to img tag <img src={selectedFile} alt="preview" />
because of type errror.
That is why I made a new state const [preview, setPreview] = useState<string>();
to preview image instead of using selectedFile
since src should be string. But this is a hassle way to set the state twice.
If you have better idea not to use double states like my code, I would really appreciate.
If possible, I would like to keep to use useState<File>()
CodePudding user response:
You should first sec the default of selectedFile
to be null
,
then set src
of image directly :
const [selectedFile, setSelectedFile] = useState<File | null>(null);
<input
onChange={(event: ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) return
setSelectedFile(event.target.files[0]);
}}
/>
<img src={selectedFile === null ? '' : URL.createObjectURL(selectedFile)} alt="preview" />