UNPKG

@unlazy/react

Version:

React lazy loading library for placeholder images

52 lines (51 loc) 1.22 kB
import { jsx } from "react/jsx-runtime"; import { useEffect, useRef } from "react"; import { autoSizes as _autoSizes, lazyLoad, triggerLoad } from "unlazy"; export function UnLazyImage({ src, srcSet, autoSizes, blurhash, thumbhash, placeholderSrc, placeholderSize, preload = false, loading = "lazy", onImageLoad, onImageError, ...rest }) { const target = useRef(null); useEffect(() => { if (!target.current) return; if (preload) { if (autoSizes) _autoSizes(target.current); triggerLoad(target.current, onImageLoad, onImageError); return; } const cleanup = lazyLoad(target.current, { hash: thumbhash || blurhash, hashType: thumbhash ? "thumbhash" : "blurhash", placeholderSize, onImageLoad, onImageError }); return () => { cleanup(); }; }, [src, srcSet, autoSizes, blurhash, thumbhash, placeholderSrc, placeholderSize, preload, onImageLoad, onImageError]); return /* @__PURE__ */ jsx( "img", { ref: target, src: placeholderSrc, "data-src": src, "data-srcset": srcSet, "data-sizes": autoSizes ? "auto" : void 0, loading, ...rest } ); }