find size of react component or image before rendering

Praveen Singh Yadav picture Praveen Singh Yadav · Jul 11, 2016 · Viewed 8.1k times · Source

I have a list of images of different sizes.

images = ['https://example.com/1.jpg','https://example.com/2.jpg', ... ]

I want to get an array of their height before rendering them. I will then only render the images which should be in viewport based on scrollHeight. e.g using React Infinte

I can do this easily outside react component

let imgHeights =  images.map(imgUrl => {
    var img  = new Image()
    img.src = imgUrl
    return img.height;
})

but new image() does not work in react since it depends on DOM.

My React component render method looks like this.

var ImageList = (images) => {
     let buildImageList = images.map(imgUrl => {
         return <img src= {imgUrl}></img>
     })

     let imgHeights = images.map(imgUrl => {
         let img = new Image()
         img.src = imgUrl
         return img.height //this doesn't work 
     })

     return (
         <Infinte elemetHeight = {imgHeights} onInfiniteLoad ={buildImageList} />
     ) 
}

How can I get The Image height? Should I use ReactDOM to render images in a temporary div?

Answer

Radio- picture Radio- · Jul 11, 2016

Images are downloaded asynchronously while the javascript continues to execute, so you need to wait for them to load in order to record their heights. You could wait on their onload event and do something like

 let imgHeights = {};
 images.forEach(imgUrl => {
     let img = new Image();
     img.src = imgUrl;
     img.onload = () => imgHeights[imgUrl] = img.height;
 })

That just gets you started; you still have to figure out how to render them as they become ready.