11import { useEffect , useRef } from 'react' ;
22
3+ const observerOptions = {
4+ root : null ,
5+ rootMargin : '0px' ,
6+ threshold : 0.5 ,
7+ } ;
8+
39export default function Video ( { src } ) {
410 const videoRef = useRef ( null ) ;
11+ const observerRef = useRef ( null ) ;
512
613 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+ }
2518
2619 return ( ) => {
27- videoRef . current && observer . unobserve ( videoRef . current ) ;
20+ if ( videoRef . current && observerRef . current ) {
21+ observerRef . current . unobserve ( videoRef . current ) ;
22+ }
2823 } ;
2924 } , [ src ] ) ;
3025
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+
3139 return (
3240 < video
3341 ref = { videoRef }
@@ -37,8 +45,6 @@ export default function Video({ src }) {
3745 loop
3846 controls
3947 className = "mt-6 rounded-xl border dark:border-zinc-800"
40- >
41- < source src = { src } type = "video/mp4" />
42- </ video >
48+ />
4349 ) ;
4450}
0 commit comments