react-lazy-img-observer
Version:
A React component for lazy loading images with Intersection Observer
112 lines (75 loc) β’ 3.46 kB
Markdown
# π· ImageLazy
**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.


## π¦ Installation
```bash
npm install react-lazy-img-observer
```
## π Usage
### Basic example (JSX or TSX)
```tsx
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" }}
/>
);
```
## π§© Props
| 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-*`). |
## π How It Works
The component uses the [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) 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.
## βοΈ Intersection Observer Configuration
- `root`: `null` (default viewport)
- `rootMargin`: `"0px"`
- `threshold`: `0.5` (50% visibility required)
## π¨ Styling
The image starts blurred and transitions smoothly once itβs loaded. You can override or enhance this with your own styles:
```css
.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.
## π License
[ISC License](./LICENSE)
## π€ Contributing
Contributions are welcome!
Feel free to [open an issue](https://github.com/perch33/react-lazy-img-observer/issues) or submit a pull request.
## π€ Author
**Percy Chuzon**
π§ contacto@percychuzon.com
π [https://percychuzon.com](https://percychuzon.com)
## π Acknowledgments
Thanks to the React community and the MDN docs for inspiration and guidance.