1 | import { useRef, useState } from 'react' |
||
2 | import { useIntersectionObserver } from 'shared/hooks/useIntersectionObserver' |
||
3 | |||
4 | interface IProps { |
||
5 | imageUrl: string |
||
6 | alt: string |
||
7 | width: string |
||
8 | height: string |
||
9 | } |
||
10 | |||
11 | export const LazyImage = ({ imageUrl, alt, width, height }: IProps) => { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
12 | const imgRef = useRef<HTMLImageElement | null>(null) |
||
13 | const [isLoaded, setLoaded] = useState<boolean>(false) |
||
14 | |||
15 | const setSrc = () => { |
||
16 | let srcRef = imgRef?.current?.src |
||
17 | srcRef = imgRef?.current?.dataset?.src |
||
0 ignored issues
–
show
|
|||
18 | imgRef?.current?.removeAttribute('data-src') |
||
19 | setLoaded(true) |
||
20 | } |
||
21 | |||
22 | useIntersectionObserver({ |
||
23 | target: imgRef, |
||
24 | onIntersect: setSrc, |
||
25 | rootMargin: '1200px', |
||
26 | enabled: !isLoaded, |
||
27 | }) |
||
28 | |||
29 | return ( |
||
30 | <img |
||
0 ignored issues
–
show
|
|||
31 | ref={imgRef} |
||
0 ignored issues
–
show
|
|||
32 | data-src={imageUrl} |
||
0 ignored issues
–
show
|
|||
33 | alt={alt} |
||
0 ignored issues
–
show
|
|||
34 | width={width} |
||
0 ignored issues
–
show
|
|||
35 | height={height} |
||
0 ignored issues
–
show
|
|||
36 | loading="lazy" |
||
0 ignored issues
–
show
|
|||
37 | /> |
||
38 | ) |
||
39 | } |
||
40 |