I am working on SSR React-based
application using NextJS
. Once DOM has been rendered I need to detect a set of elements visibility in the viewport and once they are visible I need to do something. Now to accomplish that I need the reference to that set of elements which I am taking in componentDidMount
lifecycle method, having an understanding that since DOM has been completely rendered I can grab all the elements together and watch them if they are in the viewport or not.
Below code is for taking the reference of the set of elements:
componentDidMount() {
this.imageContainer = document.getElementsByClassName("prod_images");
console.log('imageContainer -> ', this.imageContainer, 'length ->',
this.imageContainer.length, 'type is -> ', typeof this.imageContainer);
}
So, I get an HTMLCollection of a set of images which are stored in imageContainer variable. I did a console below and I get below in console :
In the above SS, I have only shown 4 entries from HTML Collection object, but I get all 141 correctly. My problem is that I am getting this.imageContainer.length as 0 in console, though the values are present. I use this.imageContainer.length, later on, to loop through the elements and at that time the value is 0.
Link -> Javascript HTML collection showing as 0 length
explains the fact that this might be due to DOM elements are not loaded by that time and we should do this check in DOMContentLoaded
. But I am already using componentDidMount lifecycle method. So what is the issue and why length is coming as 0. Is it got to do something with SSR?