0

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>()

1 Answer 1

2

You should first set 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" />
Sign up to request clarification or add additional context in comments.

3 Comments

Adding null value to default ! That makes sense. Appreciated.
I still got the error "Type 'string | false' is not assignable to type 'string | undefined'. Type 'boolean' is not assignable to type 'string'."
I've updated the solution's code src={selectedFile === null ? '' : URL.createObjectURL(selectedFile)} .. instead of src={selectedFile !== null && URL.createObjectURL(selectedFile)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.