I’m trying to implement infinite scroll on react photo album component,
I’m trying to use this library :
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
you can use From ‘react-infinite-scroller’ package.
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. AnIntersectionObserver
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 thescrollTop
of thegalleryRef
, 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. ThePhotoAlbum
component is wrapped in a scrollable container with a fixed height andoverflowY: auto
.