1.0.0 • Published 1 year ago

@enjoywater-hook/use-lazy-image v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

useLazyImage

React hook for image lazy loading.

📌

useLazyImage is custom React-Hook. So it works on only React environment.

This hook uses the Intersection Observer API to delay the loading of images.

🛠️   Installation

$ npm install @enjoywater-hook/use-lazy-image

or

$ yarn add @enjoywater-hook/use-lazy-image

📝   How To Use

  1. Add import LazyImage from "@enjoywater-hook/use-lazy-image" in your component.
  2. Add props to the LazyImage component.
<LazyImage alt="..." src="..." observerOptions={ {...} }>

/*
type

alt : string;
src : string;
observerOptions : {
  root: Element | Document;
  rootMargin: string;
  threshold: number | number[];
}

*/

    => observerOptions has the same value as the options parameter of IntersectionObserver().

  1. Put the LazyImage component at the location of the image to apply lazy loading to.

🔍   Example

  1. An example of using LazyImage without observerOptions.
import LazyImage from '@enjoywater-hook/use-lazy-image';

function Component() {
  return (
    <FoodList>
      {data.map(({ id, imageUrl }) => (
        <Food key={id}>
          <LazyImage src={imageUrl} alt="food" />
        </Food>
      ))}
    </FoodList>
  );
}

export default Component;
  1. An example of using LazyImage with observerOptions.
import LazyImage from '@enjoywater-hook/use-lazy-image';

function Component() {
  return (
    <FoodList>
      {data.map(({ id, imageUrl }) => (
        <Food key={id}>
          <LazyImage
            src={imageUrl}
            alt="food"
            observerOptions={{
              threshold: 0.1,
            }}
          />
        </Food>
      ))}
    </FoodList>
  );
}

export default Component;