1
1
import { useEffect , useRef } from 'react' ;
2
2
3
+ const observerOptions = {
4
+ root : null ,
5
+ rootMargin : '0px' ,
6
+ threshold : 0.5 ,
7
+ } ;
8
+
3
9
export default function Video ( { src } ) {
4
10
const videoRef = useRef ( null ) ;
11
+ const observerRef = useRef ( null ) ;
5
12
6
13
useEffect ( ( ) => {
7
- const options = {
8
- root : null ,
9
- rootMargin : '0px' ,
10
- threshold : 0.5 ,
11
- } ;
12
-
13
- const handleIntersection = ( entries ) => {
14
- entries . forEach ( ( entry ) => {
15
- if ( entry . isIntersecting ) {
16
- videoRef . current . play ( ) ;
17
- } else {
18
- videoRef . current . pause ( ) ;
19
- }
20
- } ) ;
21
- } ;
22
-
23
- const observer = new IntersectionObserver ( handleIntersection , options ) ;
24
- observer . observe ( videoRef . current ) ;
14
+ observerRef . current = new IntersectionObserver ( handleIntersection , observerOptions ) ;
15
+ if ( videoRef . current ) {
16
+ observerRef . current . observe ( videoRef . current ) ;
17
+ }
25
18
26
19
return ( ) => {
27
- videoRef . current && observer . unobserve ( videoRef . current ) ;
20
+ if ( videoRef . current && observerRef . current ) {
21
+ observerRef . current . unobserve ( videoRef . current ) ;
22
+ }
28
23
} ;
29
24
} , [ src ] ) ;
30
25
26
+ const handleIntersection = ( entries : IntersectionObserverEntry [ ] ) => {
27
+ entries . forEach ( ( entry : IntersectionObserverEntry ) => {
28
+ if ( entry . isIntersecting ) {
29
+ if ( ! videoRef . current . src ) {
30
+ videoRef . current . src = src ;
31
+ }
32
+ videoRef . current . play ( ) ;
33
+ } else {
34
+ videoRef . current . pause ( ) ;
35
+ }
36
+ } ) ;
37
+ } ;
38
+
31
39
return (
32
40
< video
33
41
ref = { videoRef }
@@ -37,8 +45,6 @@ export default function Video({ src }) {
37
45
loop
38
46
controls
39
47
className = "mt-6 rounded-xl border dark:border-zinc-800"
40
- >
41
- < source src = { src } type = "video/mp4" />
42
- </ video >
48
+ />
43
49
) ;
44
50
}
0 commit comments