Skip to content

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

License

Notifications You must be signed in to change notification settings

jimmy319/react-use-lazy-img

Repository files navigation

react-use-lazy-img

Component Build Npm Publish

This hook empowers components to load image lazily.

Installation

npm i react-use-lazy-img

Usage

Trigger image loading when component is rendered

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])

Name Description
imgUrl image url you want to load lazily
placeholderUrl image url that is used to display as a placeholder before the desired image loads
lazyTarget (optional) ref of a DOM element which is used to determine the timing of loading image according to its visibility
intersectionObserverOptions (optional) use intersection observer options if you want to lazyily load images in a complicated way
fallbackUrl (optional) image url which will be used when imgUrl is broken

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •