skip to Main Content

I’m trying to implement infinite scroll on react photo album component,

I’m trying to use this library :

https://react-photo-album.com

i can detect when the user scrolled down and fetch more photos (by setting intersection observer right beneath the album) the issue is when i add these photos to the state and from there to the props of the gallery component, then the component re-renders and show all the images from the top.

i can implement my own gallery component, but then it will be hard to display photos of different sizes and different ratios in a nice responsive row-or-column layout,

here is my code:

import React, { useState, useCallback, useRef } from 'react';
import PhotoAlbum from 'react-photo-album';

const [images, setImages] = useState<ImageState[]>([]);

  const lastImageObserver = useRef<IntersectionObserver>();

  const lastImageElementRef = useCallback(
    (node: any) => {
      if (lastImageObserver.current) lastImageObserver.current.disconnect();
      lastImageObserver.current = new IntersectionObserver(
        (entries) => {
          if (entries[0].isIntersecting) {
            console.log('last image is intersecting');
            if (currentPage < Math.ceil(totalImages / rowsPerPage)) {
              setCurrentPage((prevPage) => prevPage + 1);
            }
          }
        },
        {
          threshold: 0.1,
        }
      );
      if (node) lastImageObserver.current.observe(node);
    },
    [currentPage, rowsPerPage]
  );

  const fetchImages = useCallback(async () => {
    const result = await getPhotos(
      currentPage,
      rowsPerPage
    );
    const newImages = result.images;
    setImages((prev) => [...prev, ...newImages]);

  }, [currentPage totalImages]);


  return (

       <PhotoAlbum
                  layout="rows"
                  photos={images}
                />
                <div
                  ref={lastImageElementRef}
                  style={{ minHeight: '1px' }}
                ></div>
              </div>
            </div>
            )

how should i approach this issue? any help will be appreciated, thanks!

2

Answers


  1. you can use From ‘react-infinite-scroller’ package.

    npm install react-infinite-scroller –s

    import InfiniteScroll from 'react-infinite-scroller';
    
    <InfiniteScroll
        pageStart={0}
        loadMore={loadFunc}
        hasMore={true || false}
        loader={<div className="loader" key=. 
        {0}>Loading ...</div>}
     >
    
        <PhotoAlbum
            layout="rows"
            photos={images}
        />
    </InfiniteScroll>
    
    Login or Signup to reply.
  2. What went wrong:

    When new photos were added to the state, the component re-rendered, causing the gallery to scroll back to the top, disrupting the user’s scroll experience.

    What was done to prevent it:

    useEffect was used to save the current scroll position and restore it after new images are loaded. useCallback was applied to optimize the image fetching function, preventing unnecessary re-fetching. An IntersectionObserver triggers fetching more images when the last photo is visible, ensuring smooth infinite scrolling without resetting the scroll position.

    Since the scrolling occurred inside the PhotoAlbum component, not the entire page, the scroll position is now tracked using the scrollTop of the galleryRef, which represents the scrollable container. Before fetching new images, the scroll position is saved, and after the images are loaded, it is restored to prevent the scroll from resetting. The PhotoAlbum component is wrapped in a scrollable container with a fixed height and overflowY: auto.

    import React, { useState, useCallback, useRef, useEffect } from 'react';
    import PhotoAlbum from 'react-photo-album';
    
    const PhotoGallery = () => {
      const [images, setImages] = useState([]);
      const [currentPage, setCurrentPage] = useState(1);
      const [totalImages, setTotalImages] = useState(100); // Assuming total images to be fetched
      const rowsPerPage = 10; // How many images you load per fetch
      const galleryRef = useRef(null); // Ref for the scrollable container
      const lastImageObserver = useRef(null);
    
      // Function to handle fetching images
      const fetchImages = useCallback(async () => {
        const result = await getPhotos(currentPage, rowsPerPage);
        const newImages = result.images;
        setImages((prev) => [...prev, ...newImages]);
      }, [currentPage, rowsPerPage]);
    
      // Save and restore scroll position when new images are added
      useEffect(() => {
        if (galleryRef.current) {
          const scrollContainer = galleryRef.current;
          const scrollTop = scrollContainer.scrollTop; // Save scroll position
          fetchImages().then(() => {
            scrollContainer.scrollTop = scrollTop; // Restore scroll position
          });
        }
      }, [currentPage, fetchImages]);
    
      // Intersection Observer to detect when the last image is visible
      const lastImageElementRef = useCallback(
        (node) => {
          if (lastImageObserver.current) lastImageObserver.current.disconnect();
          lastImageObserver.current = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting) {
              console.log('Last image is intersecting');
              if (currentPage < Math.ceil(totalImages / rowsPerPage)) {
                setCurrentPage((prevPage) => prevPage + 1);
              }
            }
          });
          if (node) lastImageObserver.current.observe(node);
        },
        [currentPage, rowsPerPage, totalImages]
      );
    
      return (
        <div
          ref={galleryRef}
          style={{ height: '500px', overflowY: 'auto' }} // Define a scrollable container
        >
          <PhotoAlbum
            layout="rows"
            photos={images}
            onClick={(photo, index) => console.log(photo, index)}
          />
          {/* Invisible div at the end to trigger infinite scroll */}
          <div ref={lastImageElementRef} style={{ minHeight: '1px' }}></div>
        </div>
      );
    };
    
    export default PhotoGallery;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search