Aljullu / react-lazy-load-image-component

React Component to lazy load images and components using a HOC to track window scroll position.
https://www.npmjs.com/package/react-lazy-load-image-component
MIT License
1.44k stars 109 forks source link

Lazy loading images in a carousel #130

Open mbuguanewton opened 5 months ago

mbuguanewton commented 5 months ago

Hi,

Can we load images in a carousel, where for example once the first image is in view and loaded we can also load the second image without waiting until its in view?

Sample code:

import useDimensions from "react-cool-dimensions"
import { LazyloadImage, trackWindowScroll } from 'react-lazy-load-image-component';
import { Carousel, CarouselDots, CarouselNext, CarouselItem, CarouselContent, CarouselPrevious } from "@components/ui/carousel" // Shadcn Carousel Component

function Image({ children, width = 500, height = 500, ...imgProps }) {
  return (
      <LazyLoadImage
      width={width}
      effect="blur"
      height={height}
      wrapperClassName="w-full h-full"
      placeholder={
              <div
                className="w-full h-full bg-gray-50 animate-pulse"
                style={{ width, height }} />
      }
      loading="lazy"
      {...imgProps}
      />
  );
}

function GalleryCarousel({ slides, className, theme, scrollPosition }) {
    const { observe, height, width } = useDimensions();

    return (
        <Carousel opts={{ loop: true }} className={cn('h-full', className)}>
        <CarouselContent className="h-full">
                {slides.map((slide, index) => (
                <CarouselItem ref={observe} key={index} className="relative h-full">
              <Image
                    height={height || 500}
                    src={slide.src}
                    alt={slide.alt}
                    width={width || 500}
                    scrollPosition={scrollPosition}
                    className="object-cover w-full h-full"
              />
                </CarouselItem>
                ))}
        </CarouselContent>
        <CarouselDots className="absolute bg-opacity-50 bottom-8" />
        <div className="absolute z-10 flex items-center justify-between w-full h-auto -translate-y-1/2 top-1/2">
                <CarouselPrevious
                variant="unstyled"
                className={cn(
                'relative left-0 top-0 -translate-y-0 h-14 w-16 p-4 bg-white rounded-none rounded-r-full ',
                { 'bg-core-blue text-white': theme === 'dark' }
                  )} />
                <CarouselNext
                variant="unstyled"
                className={cn(
                'relative right-0 top-0 -translate-y-0 h-14 w-16 p-4 bg-white rounded-none rounded-l-full ',
                { 'bg-core-blue text-white': theme === 'dark' }
                  )} />
        </div>
        </Carousel>
    );
}

export default trackWindowScroll(GalleryCarousel)