React.js, attribute in object is undefined but exist in object with non-null value

Viewed 357

I want to add picture files with Dropzone and show preview on browser. So, I have to get src which can use at <img />. So I do this process:

  const handleAddImages = async (inputImages: any[]): Promise<void> => {
    const imagesWithSrc = inputImages.map((img) => {
      const reader = new FileReader();
      new Promise((resolve, reject) => {
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(img);
      }).then(() => (img.src = reader.result));
      return img;
    });

    const nextImages = [...currentImages, ...imagesWithSrc];
    handleOnChange({
     //set state
      target: {
        name: "images",
        value: nextImages,
      },
    });
  };

And show the images in this component:

export const FileList = ({
  images
}: any) => {
  const imgs: any[] = images;

  return (
      <Wrapper>
        {imgs.map((img, index) => (
            <ImgBox key={index}>
              <img src={img.src} />
            </ImgBox>
        ))}
      </Wrapper>
  );
};

I have an images array imgs and contains image file objects. When I do this:

console.log(imgs[0]);

it will output every attributes in image file object of index 0 including the image source src in base64 from filereader API.

but when I do this:

console.log(imgs[0].src);

it will output undefined,

even I do console.log in map like this:

imgs.map((img, index) => {
  console.log(img);
  console.log(img.src);
})

and get the same result, what is the problem?

console.log("imgs[0]", imgs[0]); 
console.log("imgs[0].src", imgs[0].src);

ouput:

enter image description here

By the way, I can get the size attribute by imgs[0].size at first, and get the imgs[0].src after add another picture.

2 Answers

As defined in the W3C File API, the File interface (which extends Blob) does NOT have an src property. While your environment may display an src property, it appears to be inaccessable from your code, and may be added by your browser's runtime or another part of your code in a way that makes it inaccessable. Honestly, without more information, I cannot say for sure where the src property is coming from.

If you want to base64-ify your File object, try using the FileReader API:

let blob = imgs[0];

let reader = new FileReader();
reader.readAsDataURL(blob);

reader.onload = function() {
  console.log(reader.result); //-> "data:image/png;base64,iVBORw..."
};
Related