react photo album infinite scroll

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!

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>

1

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;

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật