0

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);
        };

1 Answer 1

1

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';
Sign up to request clarification or add additional context in comments.

9 Comments

@YoanIvanov You need to import the typing for ChangeEvent. Does your IDE not autosuggest its import from react?
Okay but I'm getting this in the console when I console.log event SyntheticBaseEvent {_reactName: 'onChange', _targetInst: null, type: 'change', nativeEvent: Event ....
Yes, that is expected. The event emitted from an event handler in React JSX is NOT the native event but more like a custom implementation of event (hence SyntheticBaseEvent. What are you trying to achieve here?
I mean it's not the image, like Filelist. The name of image, path of image ... So can I use it like that ?
When you log files as per my code, what do you see? Hint: you will see the FileList.
|

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.