Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify type for file upload event in react typescript

I don't quite understand how event typing works, I'd like to specify a type here, but cannot quite figure out how to do it. I cannot seem to find a type reference for this specific case.

private handleChange (event /*:FileUplaodEvent or something */): void {
    this.setState ({
      csv: event.target.files[0],
    });
}

Any help would be appreciated...

edit: As answer by Mukesh Soni stated I used React.FormEvent<HTMLInputElement>, but for whatever reason the interface for files is a bit different for this type, it is actually: event.currentTarget.files rather than event.target.files.

like image 280
Grigory Bogush Avatar asked Aug 13 '19 08:08

Grigory Bogush


People also ask

What is type of event in react typescript?

Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent . As well as SyntheticEvent , for all other events.

How do you handle file input in react?

files[0]) } function handleSubmit(event) { event. preventDefault() const url = 'http://localhost:3000/uploadFile'; const formData = new FormData(); formData. append('file', file); formData. append('fileName', file.name); const config = { headers: { 'content-type': 'multipart/form-data', }, }; axios.

How do I upload a file using react hook form?

Multipart File Upload with React Hook Form​ To manage our form and its elements, we defined the register and handleSubmit methods from the react hook form. Now, let's upload the file selected in our onSubmit method to our server by placing it in the formData. export default App; Our project is ready!


1 Answers

The accepted answer didn't work for me.

If you want to access e.target.files or e.currentTarget.files You should use React.ChangeEvent<HTMLInputElement> as the event type .

Example:

const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) {
      return;
    }

    // handle the input...
    console.log(e.target.files);
}


<Input type='file' onChange={handleChange}/>
like image 169
Sebastiaan Avatar answered Sep 22 '22 05:09

Sebastiaan