From c0bedc33d0615591c2c7d3469ff5c12959ce0a73 Mon Sep 17 00:00:00 2001 From: yun-cheng Date: Sat, 23 Mar 2024 22:06:41 +0800 Subject: [PATCH 1/2] feat(component): add common use LazyImage component --- src/components/common/LazyImage.tsx | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/components/common/LazyImage.tsx diff --git a/src/components/common/LazyImage.tsx b/src/components/common/LazyImage.tsx new file mode 100644 index 0000000..a053dbc --- /dev/null +++ b/src/components/common/LazyImage.tsx @@ -0,0 +1,38 @@ +import type { ComponentProps, ReactElement } from 'react' +import { useInView } from 'react-intersection-observer' +import cn from 'utils/cn' + +type Props = ComponentProps<'img'> & { + rootSelector?: string + rootMargin?: string +} + +export default function LazyImage({ + src, + alt, + rootSelector = undefined, + rootMargin = '250px 0px', + className, + ...props +}: Props): ReactElement { + const { ref, inView } = useInView({ + root: rootSelector ? document.querySelector(rootSelector) : undefined, + triggerOnce: true, + rootMargin + }) + + return ( +
+
+ {!!inView && ( + {alt} + )} +
+ ) +} From da57f53f207050c7f1fc2d8618f3d5f9934da6a6 Mon Sep 17 00:00:00 2001 From: yun-cheng Date: Sat, 23 Mar 2024 22:08:57 +0800 Subject: [PATCH 2/2] feat(ResultsPage): implement lazy loading for result images --- src/components/result/ResultItem.tsx | 8 +++++++- src/pages/ResultsPage.tsx | 8 ++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/components/result/ResultItem.tsx b/src/components/result/ResultItem.tsx index 31bb167..12c2875 100644 --- a/src/components/result/ResultItem.tsx +++ b/src/components/result/ResultItem.tsx @@ -1,3 +1,4 @@ +import LazyImage from 'components/common/LazyImage' import type { ReactElement } from 'react' import type { Result } from 'types/result' import cn from 'utils/cn' @@ -11,7 +12,12 @@ export default function ResultItem({ }: Props): ReactElement { return (
- avatar +
-
+