File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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 } ;
You can’t perform that action at this time.
0 commit comments