Skip to content

Commit c18ec6b

Browse files
committed
show loader on scroll down event
1 parent 82d4b90 commit c18ec6b

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

src/components/react/Gallery.tsx

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import type { FC } from 'react';
1212

1313
import 'photoswipe/style.css';
1414

15+
import useScrollDown from './hooks/useScrollDown';
16+
1517
interface Props {
1618
images: GalleryImage[];
1719
}
@@ -30,6 +32,8 @@ const Gallery: FC<Props> = ({ images }) => {
3032
const [page, setPage] = useState<number>(INITIAL_PAGE);
3133
const observerTarget = useRef(null);
3234

35+
const isScrollingDown = useScrollDown();
36+
3337
const [loadedStates, setLoadedStates] = useState<LoadedStates>({});
3438

3539
// calculate if new page is loaded on scroll
@@ -41,6 +45,8 @@ const Gallery: FC<Props> = ({ images }) => {
4145

4246
const isEnd = loadedImages.length === images.length;
4347

48+
const shouldShowLoader = isScrollingDown && !isEnd && !isLoadingPageImages;
49+
4450
// converts page to loaded images
4551
useEffect(() => {
4652
const upToPageImages = fetchImagesUpToPage(images, page);
@@ -121,15 +127,15 @@ const Gallery: FC<Props> = ({ images }) => {
121127

122128
<div
123129
className={cn(
124-
'flex items-center justify-center transition-all duration-300 ease-in-out',
125-
isLoadingPageImages ? 'min-h-32' : 'min-h-0'
130+
'flex items-center justify-center transition-all duration-500 ease-in-out',
131+
shouldShowLoader ? 'min-h-48' : 'min-h-0'
126132
)}
127133
>
128-
{isLoadingPageImages && <PiSpinnerGapBold className="size-12 animate-spin mt-4" />}
134+
{shouldShowLoader && <PiSpinnerGapBold className="size-10 sm:size-12 animate-spin mt-4" />}
129135
</div>
130136

131137
{/* control threshold with margin-top */}
132-
<div ref={observerTarget} className="mt-0"></div>
138+
<div ref={observerTarget} className="mt-0" />
133139
</>
134140
);
135141
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { useEffect, useState } from 'react';
2+
3+
const useScrollDown = (): boolean => {
4+
const [isScrollingDown, setIsScrollingDown] = useState(false);
5+
const [lastScrollTop, setLastScrollTop] = useState(0);
6+
7+
useEffect(() => {
8+
const handleScroll = () => {
9+
const currentScroll = window.scrollY;
10+
setIsScrollingDown(currentScroll > lastScrollTop);
11+
setLastScrollTop(currentScroll);
12+
};
13+
14+
window.addEventListener('scroll', handleScroll);
15+
return () => window.removeEventListener('scroll', handleScroll);
16+
}, [lastScrollTop]);
17+
18+
return isScrollingDown;
19+
};
20+
21+
export default useScrollDown;

0 commit comments

Comments
 (0)