Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to upload image as file in React with TypeScript

I’m trying to upload image as file but I’m not sure how to do it exactly.

Here is my input:

<input type="file" name="image" placeholder='Image' onChange={e => handleSetImage(e, i)}/>

Here is the error for "e":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Argument of type ‘ChangeEvent’ is not assignable to
parameter of type ‘FileList’. Type ‘ChangeEvent’
is missing the following properties from type ‘FileList’: length,
item, [Symbol.iterator]ts(2345)

And here is my handler:

const [colorsAndImages, setColorsAndImages] = useState<[{image: object, color: string}]>([{image: {}, color: ''}])

...

    const handleSetImage = (event: FileList, index: number) => {
            const files = event;
            const list = [...colorsAndImages]
            list[index][image] = list
            console.log(list);
        };

>Solution :

That is because you have incorrectly typed your event argument in your handleSetImage. Based on how you’re calling it, i.e.:

onChange={e => handleSetImage(e, i)}

You’re actually passing ChangeEvent<HTMLInputElement> as e into your function. Therefore you need to update its typing accordingly:

const handleSetImage = (event: ChangeEvent<HTMLInputElement>, index: number) {
  const { files } = event.target;

  // Or if you don't prefer Object destructuring assignment...
  // const files = event.target.files;

  // Rest of the logic here
}

That requires you to import the typing for ChangeEvent from the react library, if your IDE fails to auto import it automatically:

import { ChangeEvent } from 'react';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading