ImageLazy is a lightweight React component for lazy loading images using the Intersection Observer API. It delays the loading of off-screen images until they appear in the viewport, helping optimize performance and reduce initial load times.
npm install react-lazy-img-observer
import ImageLazy from "react-lazy-img-observer";
const Example = () => (
<ImageLazy
src="https://example.com/image.jpg"
alt="Description of the image"
width={600}
height={400}
className="custom-class"
id="image-1"
title="Image title"
extraData={{ "data-custom": "value" }}
/>
);
Prop | Type | Required | Description |
---|---|---|---|
src |
string |
β | The source URL of the image. |
alt |
string |
β | The alt text for accessibility. |
width |
number |
β | The width of the image. |
height |
number |
β | The height of the image. |
id |
string | number |
β | Optional ID for the image element. |
className |
string |
β | CSS class for custom styling. |
title |
string |
β | Tooltip text shown on hover. |
extraData |
React.ImgHTMLAttributes<HTMLImageElement> |
β | Any extra HTML attributes (e.g., data-* ). |
The component uses the IntersectionObserver
API to detect when the image enters the viewport. Once at least 50% of the image is visible, the real src
is assigned to the image, triggering the browser to load it.
-
root
:null
(default viewport) -
rootMargin
:"0px"
-
threshold
:0.5
(50% visibility required)
The image starts blurred and transitions smoothly once itβs loaded. You can override or enhance this with your own styles:
.custom-class {
filter: blur(20px);
transition: filter 0.9s ease;
}
.custom-class.loaded {
filter: none;
}
You may also override the style
prop directly if preferred.
Contributions are welcome!
Feel free to open an issue or submit a pull request.
Percy Chuzon
π§ contacto@percychuzon.com
π https://percychuzon.com
Thanks to the React community and the MDN docs for inspiration and guidance.