2022-12-29 00:43:22 +01:00
|
|
|
import { useState, useRef, useEffect } from 'react';
|
2020-08-02 08:37:46 +02:00
|
|
|
|
2020-08-04 08:20:35 +02:00
|
|
|
function isInViewport(element) {
|
|
|
|
const rect = element.getBoundingClientRect();
|
|
|
|
return !(
|
|
|
|
rect.bottom < 0 ||
|
|
|
|
rect.right < 0 ||
|
|
|
|
rect.left > window.innerWidth ||
|
|
|
|
rect.top > window.innerHeight
|
2020-08-02 08:37:46 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-08-04 08:20:35 +02:00
|
|
|
export default function CheckVisible({ className, children }) {
|
2020-08-02 08:37:46 +02:00
|
|
|
const [visible, setVisible] = useState(false);
|
|
|
|
const ref = useRef();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const checkPosition = () => {
|
|
|
|
if (ref.current) {
|
|
|
|
const state = isInViewport(ref.current);
|
|
|
|
if (state !== visible) {
|
|
|
|
setVisible(state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
checkPosition();
|
|
|
|
|
|
|
|
window.addEventListener('scroll', checkPosition);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('scroll', checkPosition);
|
|
|
|
};
|
|
|
|
}, [visible]);
|
|
|
|
|
2020-08-04 08:20:35 +02:00
|
|
|
return (
|
|
|
|
<div ref={ref} className={className} data-visible={visible}>
|
|
|
|
{typeof children === 'function' ? children(visible) : children}
|
|
|
|
</div>
|
|
|
|
);
|
2020-08-02 08:37:46 +02:00
|
|
|
}
|