| 1 |
import React, { useEffect, useMemo, useRef, useState } from "react"; |
| 2 |
|
| 3 |
/** |
| 4 |
* Props for InView component. |
| 5 |
*/ |
| 6 |
interface InViewProps { |
| 7 |
children: React.ReactNode; |
| 8 |
viewRatio?: number; |
| 9 |
classNames?: string[]; |
| 10 |
} |
| 11 |
|
| 12 |
/** |
| 13 |
* Component to render children when they are in view. |
| 14 |
* |
| 15 |
* @param props Component props. |
| 16 |
* @param props.children Component to render when in view. |
| 17 |
* @param [props.viewRatio=0.1] Ratio of the element that needs to be in view to trigger the render. (1.0 being fully in view) |
| 18 |
* |
| 19 |
* @param [props.classNames=[]] Additional class names to apply to the wrapper. |
| 20 |
* @class |
| 21 |
*/ |
| 22 |
const InView: React.FC<InViewProps> = ({ |
| 23 |
children, |
| 24 |
viewRatio = 0.1, |
| 25 |
classNames = [], |
| 26 |
}) => { |
| 27 |
const [isInView, setIsInView] = useState(false); |
| 28 |
|
| 29 |
const wrapperRef = useRef(null); |
| 30 |
|
| 31 |
// Component observer initialization. |
| 32 |
const observer = useMemo( |
| 33 |
() => |
| 34 |
new IntersectionObserver( |
| 35 |
([entry]) => { |
| 36 |
const { isIntersecting } = entry; |
| 37 |
|
| 38 |
// only update state if element is in view |
| 39 |
if (isIntersecting) { |
| 40 |
setIsInView(isIntersecting); |
| 41 |
} |
| 42 |
}, |
| 43 |
{ threshold: viewRatio } |
| 44 |
), |
| 45 |
[viewRatio] |
| 46 |
); |
| 47 |
|
| 48 |
// Class list for the wrapper. |
| 49 |
const classList = useMemo( |
| 50 |
() => ["tableberg-in-view-wrapper", ...classNames].join(" "), |
| 51 |
[classNames] |
| 52 |
); |
| 53 |
|
| 54 |
useEffect(() => { |
| 55 |
if (wrapperRef.current) { |
| 56 |
observer.observe(wrapperRef.current); |
| 57 |
} |
| 58 |
}, [observer, wrapperRef]); |
| 59 |
|
| 60 |
// disconnect observer when component is in view to prevent multiple calls |
| 61 |
useEffect(() => { |
| 62 |
if (isInView) { |
| 63 |
observer.disconnect(); |
| 64 |
} |
| 65 |
}, [observer, isInView]); |
| 66 |
|
| 67 |
return ( |
| 68 |
<div className={classList} ref={wrapperRef}> |
| 69 |
{isInView && children} |
| 70 |
</div> |
| 71 |
); |
| 72 |
}; |
| 73 |
|
| 74 |
export default InView; |
| 75 |
|