How to get image dimensions from <input type="file"> with React & TypeScript before upload?

Viewed 1068

I'm trying to get image dimensions before upload with React & TypeScript.

this is my code:

<input
  //...
  type="file"
  accept="image/png, image/jpeg"
  onChange={(e) => {
    const ev = e.currentTarget.files;
    if (ev) {
      if (ev.length === 0) {
        return;
      }
      var img: HTMLImageElement;
      img = document.createElement("img");

      img.onload = function (event) {
        console.log({ width: event.width, height: event.height });
      };

      img.src = URL.createObjectURL(eventFiles[0]);
    }
    //...
  }}
/>

but I get this type error:

Property 'width' does not exist on type 'Event'.ts(2339)

What is the correct type for event and is this correct way?

1 Answers

The error in your code is that object of the source is not the event, it's img itself. You can try the following changes

img.onload = function () {
              console.log({ width: img.width, height: img.height });
            };
Related