Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find size of react component or image before rendering

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?

like image 926
Praveen Singh Yadav Avatar asked Jul 11 '16 17:07

Praveen Singh Yadav


1 Answers

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.

like image 158
Radio- Avatar answered Nov 01 '22 02:11

Radio-