How to upload image as file in React with TypeScript

Advertisements

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":

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';

Leave a ReplyCancel reply