Total Complexity | 7 |
Complexity/F | 0 |
Lines of Code | 40 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
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) => { |
||
|
|||
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 |
||
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 |
||
31 | ref={imgRef} |
||
32 | data-src={imageUrl} |
||
33 | alt={alt} |
||
34 | width={width} |
||
35 | height={height} |
||
36 | loading="lazy" |
||
37 | /> |
||
38 | ) |
||
39 | } |
||
40 |