Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Typescript: Get files from file input

The error I get is Property 'files' does not exist on type 'ChangeEvent<HTMLInputElement> Why cant I access the files array from the file input?

Is this a case where useRef is ok to use?

import React from 'react';
const Photo: React.FC = () => {

  const [state, setState] = useState({
    photo: '',
  });

  const {
    photo,
  } = state;

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
'ChangeEvent<HTMLInputElement>
    event.persist();
    setState((prev) => ({
      ...prev,
      [event.target.id]: event.target.value,
    }));
    console.log(state.photo) // returns nothing
    console.log(event.files[0]);
//                      ^
//                      Property 'files' does not exist on type 
  };

  return (
    <div className='photo'>
      <label>
        Click Me
        <input
          type='file'
          id='photo'
          name='photo'
          accept='image/png, image/jpeg'
          onChange={onChange}
          value={photo}
        ></input>
      </label>
    </div>
  );
};

like image 517
Bill Avatar asked Dec 08 '19 06:12

Bill


2 Answers

files is property of an input (HTMLInputElement) and not of the event.

So it should be event.currentTarget.files

like image 122
Aleksey L. Avatar answered Oct 18 '22 15:10

Aleksey L.


    console.log(state.photo) // returns nothing

This returns nothing because when you set state its value is available on the next render cycle. So if you select another file with your file input, then, console.log(state.photo) will log the previous file name.

If you want to log the current selected file, use:

    console.log(event.target.value)

Take a look at my example: https://codesandbox.io/s/pensive-cdn-1fnuv

And

    console.log(event.files[0]);

will throw error. Don't use it.

like image 43
Emech Avatar answered Oct 18 '22 15:10

Emech