react-sumail-lazy
v1.0.0
Published
a tiny lazyload library made by miracle_sumail, use IntersectionObserver API to accompanish this functionality
Downloads
3
Readme
a tiny lazyload library made by miracle_sumail, use IntersectionObserver API to accompanish this functionality
1. see the code inside, make use of react hooks
const LazyBox: React.FC<any> = ({className, children, threshold}) => {
const ref: any = useRef(null);
let [visible, setVisible] = useState(false);
// let [io] = useObserver({visible, setVisible});
const io = useMemo(() => (new IntersectionObserver((entries) => {
console.log(entries);
if(entries[0].isIntersecting && !visible){
setVisible(!visible)
}
console.log(visible);
if(!entries[0].isIntersecting && visible) {
setVisible(false)
}
}, {
threshold
})), [visible])
useEffect(() => {
io.observe(ref.current);
return () => {
console.log('finish');
io.unobserve(ref.current);
};
}, [visible])
return <div className={className} ref={ref}>
{visible ? children : null}
</div>
}
just a total of 34 lines, so tiny...
2. how to use
render() {
return (
<>
<LazyBox className={'lazybox'} threshold={[.2]}>
<div>fwegwgwgg</div>
</LazyBox>
</>
)
}