3

Up until a few days ago, my implementation of LazyLoad was working perfectly, but now I can't seem to get it to work.

This is my component:

import React from 'react';
import LazyLoad from 'react-lazyload';
import './image.scss';

const Image = image => (

  <LazyLoad height={200} offset={100} once>

    <div
    className="image-container"
    orientation={image.orientation}>    

      <img
      className="image"
      src={image.url}
      alt={image.alt}
      />

      {'caption' in image &&
        <div className="meta">
          <p className="caption">{image.caption}</p>
          <p className="order">{image.currentNumber}/{image.maxNumber}</p>
        </div>
      }

    </div>

  </LazyLoad>  
)

export default Image

And in App.js it is called like this:

render() {

        return (
            <div className="wrapper">

                <GalleryTop details={this.state.gallery_top} />

                {this.state.images.map((image, index) => <Image key={index} {...image} /> )}
          </div>
        )
    }

But it won't work! Here's the demo environment: https://gifted-kare-1c0eba.netlify.com/

(Check Network tab in Inspector to see that images are all requested from initial load)

There's also a video here

Any idea about what I am doing wrong?

Thanks in advance, Morten

mortenbjoern
  • 31
  • 1
  • 3
  • I am not really familiar with `react-lazyload`, but from reading the readme of the repo, it could be that `img` needs to be a direct child of `LazyLoad`. Could you try that? – Jackyef Apr 13 '20 at 15:59

1 Answers1

5

I ran into similar issues with the npm package react-lazyload. For one, this package only allows one child per LazyLoad component, so you would have to rearrange your hierarchy to make it work. Secondly, I found some strange behaviors when loading images that were already set within the viewport. The documentation does list import {forceCheck} from 'react-lazyload'; combined with forceCheck(); as a means of manually checking the elements, but I found this inconvenient and insufficient for components that aren't rerendering.

I was able to obtain the exact same functionalities with an easier implementation from the alternative package react-lazy-load. Mind the hyphen. This package also requires node>0.14. More or less, it does the same thing. You can read their documentation here: react-lazy-load

ZontarZon
  • 584
  • 6
  • 15
  • 1
    to add on to people who found this page, forceCheck should be use in useEffect of the component, with the props as dependency. In most case, you are using Lazyload and render an array of elements using .map. When the array of elements is changed (herein props), you should call for a forceCheck so lazyload will recheck the viewport to render any items to be displayed in the viewport – Someone Special Nov 27 '20 at 09:19
  • 2
    react-lazy-load doesn't support React 17. Check the dependency list before you try it. – VanAlbert Mar 04 '21 at 12:39