Mehrdad Davoudi
Mehrdad Davoudi

Reputation: 459

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

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?

Upvotes: 2

Views: 3306

Answers (1)

zixiCat
zixiCat

Reputation: 1059

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

Upvotes: 3

Related Questions