UNPKG

react-lazy-img-observer

Version:

A React component for lazy loading images with Intersection Observer

41 lines (40 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ImageLazy = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const ImageLazy = ({ src, alt, width, height, className, id, extraData, title, }) => { const imageRef = (0, react_1.useRef)(null); const [isIntersecting, setIsIntersecting] = (0, react_1.useState)(false); (0, react_1.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 ((0, jsx_runtime_1.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 })); }; exports.ImageLazy = ImageLazy; exports.default = ImageLazy;