1.0.0 • Published 1 year ago
@enjoywater-hook/use-lazy-image v1.0.0
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
- Add
import LazyImage from "@enjoywater-hook/use-lazy-image"
in your component. - Add
props
to theLazyImage
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().
- Put the
LazyImage
component at the location of the image to apply lazy loading to.
🔍 Example
- 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;
- 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;
1.0.0
1 year ago