@sr3k4nth/lazy-image-react
Version:
Lightweight react component to lazy load images.
28 lines (27 loc) • 1.52 kB
JavaScript
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
const LazyImage = ({ placeholderSrc, placeholderClassName, placeholderStyle, src, alt, className, style, }) => {
const [isLoading, setIsLoading] = useState(true);
const [isPlaceholder, setIsPlaceholder] = useState(false);
const [view, setView] = useState("");
const placeholderRef = useRef(null);
const imageRef = useRef(null);
useEffect(() => {
if (document.readyState === "complete") {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setView(src);
if (placeholderRef.current) {
observer.unobserve(placeholderRef.current);
}
}
});
if (placeholderRef.current && isPlaceholder) {
observer.observe(placeholderRef.current);
}
return () => observer.disconnect();
}
}, [src, isPlaceholder]);
return (_jsxs(_Fragment, { children: [isLoading && (_jsx("img", { src: placeholderSrc, alt: "", className: placeholderClassName, style: placeholderStyle, ref: placeholderRef, onLoad: () => setIsPlaceholder(true) })), _jsx("img", { src: view, alt: alt, className: className, onLoad: () => setIsLoading(false), style: isLoading ? { display: "none" } : style, ref: imageRef })] }));
};
export default LazyImage;