-
Notifications
You must be signed in to change notification settings - Fork 28.3k
/
Copy pathpolyfill.tsx
50 lines (42 loc) · 1.29 KB
/
polyfill.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useEffect, useRef, useState } from 'react'
import Script from 'next/script'
import s from '../styles/polyfill.module.css'
export default function Polyfill() {
const ref = useRef<HTMLSpanElement>(null)
const [lastIntersection, setIntersection] = useState(new Date())
useEffect(() => {
const observer = new IntersectionObserver(
(intersections) => {
const isIntersecting = intersections[0]?.isIntersecting
if (isIntersecting) {
setIntersection(new Date())
}
},
{
rootMargin: '45px',
}
)
if (ref.current) {
observer.observe(ref.current)
}
return () => observer.disconnect()
}, [])
return (
<>
{/* We ensure that intersection observer is available by polyfilling it */}
<Script
src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserverEntry%2CIntersectionObserver"
strategy="beforeInteractive"
/>
<main className={s.container}>
<h1>IntersectionObserver Polyfill</h1>
<h5>Scroll down to see when was the last intersection</h5>
<section className={s.section}>
<span ref={ref}>
Last intersection at {lastIntersection.toTimeString()}
</span>
</section>
</main>
</>
)
}