Skip to content

Commit 8a9740d

Browse files
committed
feature: 이미지 지연 로드를 하기 위한 LazyImage 컴포넌트 생성
1 parent 6d5688d commit 8a9740d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/components/lazy-image.tsx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import React, { useRef } from 'react';
2+
import { useInView } from '@/hooks/use-in-view';
3+
4+
type ImageProps = Omit<React.ImgHTMLAttributes<HTMLImageElement>, 'alt'> & {
5+
alt: string;
6+
};
7+
8+
const LazyImage = ({ alt, src, srcSet, ...props }: ImageProps) => {
9+
const imageRef = useRef<HTMLImageElement>(null);
10+
11+
const handleIntersectImage = () => {
12+
const $img = imageRef.current;
13+
14+
if (!$img) {
15+
return;
16+
}
17+
18+
if ($img.dataset.src) {
19+
$img.src = $img.dataset.src;
20+
}
21+
22+
if ($img.dataset.srcset) {
23+
$img.srcset = $img.dataset.srcset;
24+
}
25+
};
26+
27+
const { ref } = useInView<HTMLImageElement>(handleIntersectImage, { triggerOnce: true });
28+
29+
const handleSetRef = ($img: HTMLImageElement | null) => {
30+
ref.current = $img;
31+
imageRef.current = $img;
32+
};
33+
34+
return <img ref={handleSetRef} alt={alt} data-src={src} data-srcset={srcSet} {...props} />;
35+
};
36+
37+
export { LazyImage };

0 commit comments

Comments
 (0)