react-lazy-img-observer
Version:
A React component for lazy loading images with Intersection Observer
38 lines (37 loc) • 1.46 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
const ImageLazy = ({ src, alt, width, height, className, id, extraData, title, }) => {
const imageRef = useRef(null);
const [isIntersecting, setIsIntersecting] = useState(false);
useEffect(() => {
if (typeof IntersectionObserver === "undefined" ||
!imageRef.current) {
return;
}
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsIntersecting(true);
if (imageRef.current) {
imageRef.current.src = imageRef.current.dataset.src || "";
}
observer.unobserve(entry.target);
}
});
}, {
root: null,
rootMargin: "0px",
threshold: 0.5,
});
observer.observe(imageRef.current);
return () => {
observer.disconnect();
};
}, [src]);
return (_jsx("img", { ref: imageRef, "data-src": src, alt: alt, title: title, className: className, width: width, height: height, loading: "lazy", id: id?.toString(), style: {
filter: isIntersecting ? "none" : "blur(20px)",
transition: "filter 0.9s",
}, ...extraData }));
};
export default ImageLazy;
export { ImageLazy };