0.0.7 • Published 4 years ago

react-use-lazy-img v0.0.7

Weekly downloads
1
License
MIT
Repository
-
Last release
4 years ago

react-use-lazy-img

This hook empowers components to be able to load image lazily without any DOM/Component structure changes.

Installation

npm i -S react-use-lazy-img

Usage

Trigger image loading when component is rendered (componentDidMount)

import React from "react";
import useLazyImg from "react-use-lazy-img";

function LazyImage({ imgUrl, placeholderUrl, fallbackUrl }) {
  const { imgSrc, onError } = useLazyImg(
    imgUrl,
    placeholderUrl,
    null,
    null,
    fallbackUrl
  );
  return <img src={imgSrc} onError={onError} />;
}

Load image when the element you specified is visible

import React, { useRef } from "react";
import useLazyImg from "react-use-lazy-img";

function LazyImage({ imgUrl, placeholderUrl, fallbackUrl }) {
  const imgElement = useRef(null);
  const { imgSrc, onError } = useLazyImg(
    imgUrl,
    placeholderUrl,
    imgElement,
    null,
    fallbackUrl
  );
  return <img src={imgSrc} ref={imgElement} onError={onError} />;
}

API

useLazyImg(imgUrl, placeholderUrl, lazyTarget, intersectionObserverOptions)

NameDescription
imgUrlimage url you want to load lazily
placeholderUrlimage url which will be used to display as placeholder before desired image loaded
lazyTarget(optional) ref of a dom element which will be used to determine the timing of loading image according to its visibility
intersectionObserverOptions(optional) use intersection observer options to defer image loading if you want to do this in a complicated way
fallbackUrl(optional) image url which will be used when imgUrl is broken
0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago