react-lazy-img-observer 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENCE.md ADDED
@@ -0,0 +1,21 @@
1
+ ISC License (ISC)
2
+
3
+ Copyright (c) 2023 Percy Saul Rondan Chuzon
4
+
5
+ Se concede permiso, de forma gratuita, a cualquier persona que obtenga una copia
6
+ de este software y de los archivos de documentación asociados (el "Software"),
7
+ para tratar el Software sin restricción, incluidos, entre otros, los derechos de
8
+ uso, copia, modificación, fusión, publicación, distribución, sublicencia y/o
9
+ venta de copias del Software y para permitir a las personas a las que se les
10
+ proporcione el Software a hacerlo, sujeto a las siguientes condiciones:
11
+
12
+ El aviso de copyright anterior y este aviso de permisos se incluirán en todas
13
+ las copias o partes sustanciales del Software.
14
+
15
+ EL SOFTWARE SE PROPORCIONA "TAL CUAL", SIN GARANTÍA DE NINGÚN TIPO, EXPRESA O
16
+ IMPLÍCITA, INCLUYENDO PERO NO LIMITADO A LAS GARANTÍAS DE COMERCIABILIDAD,
17
+ IDONEIDAD PARA UN PROPÓSITO PARTICULAR Y NO INFRACCIÓN. EN NINGÚN CASO LOS
18
+ AUTORES O TITULARES DE DERECHOS DE AUTOR SERÁN RESPONSABLES DE NINGUNA
19
+ RECLAMACIÓN, DAÑO U OTRA RESPONSABILIDAD, YA SEA EN UNA ACCIÓN DE CONTRATO,
20
+ AGRAVIO O DE OTRO MODO, DERIVADA DE, FUERA DE O EN CONEXIÓN CON EL SOFTWARE
21
+ O EL USO U OTROS TRATOS EN EL SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # ImageLazy Component
2
+
3
+ The `ImageLazy` component is a React component designed for lazy loading images. It leverages the Intersection Observer API to load images only when they are within the viewport, optimizing the loading performance of your web application.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install react-lazy-img-observer
9
+ ```
10
+
11
+ # Usage
12
+
13
+ ```javascript
14
+ import ImageLazy from "react-lazy-img-observer";
15
+
16
+ const Example = () => {
17
+ return (
18
+ <ImageLazy
19
+ src="path/to/your/image.jpg"
20
+ alt="Description of the image"
21
+ width={600}
22
+ height={400}
23
+ className="your-class-name"
24
+ id="unique-image-id"
25
+ title="Image Title"
26
+ extraData={{ "data-custom-attribute": "value" }}
27
+ />
28
+ );
29
+ };
30
+ ```
31
+
32
+ ## Props
33
+
34
+ The ImageLazy component accepts the following props:
35
+
36
+ | Prop | Type | Default | Description |
37
+ | ----------- | ------------------------------------------- | ------- | --------------------------------------------------- |
38
+ | `src` | `string` | - | The source URL of the image. |
39
+ | `alt` | `string` | - | The alt text for the image. |
40
+ | `width` | `number` | - | The width of the image. |
41
+ | `height` | `number` | - | The height of the image. |
42
+ | `id` | `number \| string` | - | The ID of the image element. |
43
+ | `className` | `string` | - | Additional class names for the image element. |
44
+ | `title` | `string` | - | The title attribute for the image element. |
45
+ | `extraData` | `React.ImgHTMLAttributes<HTMLImageElement>` | - | Additional attributes to pass to the image element. |
46
+
47
+
48
+ ## Example
49
+
50
+ ```javascript
51
+ import React from 'react';
52
+ import ImageLazy from 'your-library-name';
53
+
54
+ const App = () => {
55
+ return (
56
+ <div>
57
+ <h1>Lazy Loaded Images</h1>
58
+ <ImageLazy
59
+ src="https://example.com/image1.jpg"
60
+ alt="Image 1"
61
+ width={600}
62
+ height={400}
63
+ className="image-class"
64
+ id="image1"
65
+ title="First Image"
66
+ />
67
+ <ImageLazy
68
+ src="https://example.com/image2.jpg"
69
+ alt="Image 2"
70
+ width={600}
71
+ height={400}
72
+ className="image-class"
73
+ id="image2"
74
+ title="Second Image"
75
+ />
76
+ </div>
77
+ );
78
+ };
79
+
80
+ export default App;
81
+
82
+ ```
83
+
84
+ ## How it works
85
+
86
+ The `ImageLazy` component uses the IntersectionObserver API to detect when the image enters the viewport. When the image is about to enter the viewport (50% visibility by default), the component sets the `src` attribute of the image element to load the actual image.
87
+
88
+ ## Intersection Observer Options
89
+
90
+ - **`root`**: The element that is used as the viewport for checking visibility of the target. Defaults to `null` (the browser viewport).
91
+ - **`rootMargin`**: Margin around the root. Can be used to grow or shrink the area used for intersection. Defaults to `"0px"`.
92
+ - **`threshold`**: A single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed. Defaults to `0.5`.
93
+
94
+
95
+ ## Styling
96
+
97
+ The `ImageLazy` component applies a blur filter to the image until it is fully loaded. You can customize the transition effect and blur amount through the `style` prop or CSS class.
98
+
99
+ ```css
100
+ .image-class {
101
+ filter: blur(10px);
102
+ transition: filter 0.9s;
103
+ }
104
+
105
+ .image-class[data-src] {
106
+ filter: none;
107
+ }
108
+
109
+ ```
110
+
111
+ ## License
112
+
113
+ MIT
114
+
115
+ ## Contributing
116
+
117
+ Contributions are welcome! Please open an issue or submit a pull request for any bugs or feature requests.
118
+
119
+ ## Author
120
+
121
+ Percy Chuzon
122
+
123
+ ## Acknowledgments
124
+
125
+ Thanks to the React and Intersection Observer API documentation for guidance.
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const jsx_runtime_1 = require("react/jsx-runtime");
4
+ const react_1 = require("react");
5
+ const ImageLazy = ({ src, alt, width, height, className, id, extraData, title, }) => {
6
+ const imageRef = (0, react_1.useRef)(null);
7
+ const [isIntersecting, setIsIntersecting] = (0, react_1.useState)(false);
8
+ (0, react_1.useEffect)(() => {
9
+ const observer = new IntersectionObserver((entries) => {
10
+ entries.forEach((entry) => {
11
+ if (entry.isIntersecting) {
12
+ setIsIntersecting(true);
13
+ if (imageRef.current) {
14
+ imageRef.current.src = imageRef.current.dataset.src || "";
15
+ }
16
+ observer.unobserve(entry.target);
17
+ }
18
+ });
19
+ }, { root: null, rootMargin: "0px", threshold: 0.5 });
20
+ if (imageRef.current) {
21
+ observer.observe(imageRef.current);
22
+ }
23
+ return () => {
24
+ if (imageRef.current) {
25
+ observer.unobserve(imageRef.current);
26
+ }
27
+ };
28
+ }, [src]);
29
+ return ((0, jsx_runtime_1.jsx)("img", { title: title, className: className, loading: "lazy", ref: imageRef, "data-src": src, alt: alt, width: width, height: height, style: {
30
+ filter: isIntersecting ? "none" : "blur(20px)",
31
+ transition: "filter 0.9s",
32
+ }, id: id?.toString(), ...extraData }));
33
+ };
34
+ exports.default = ImageLazy;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),ImageLazy=({src:e,alt:t,width:r,height:s,className:a,id:n,extraData:c,title:i})=>{const u=(0,react_1.useRef)(null),[o,l]=(0,react_1.useState)(!1);return(0,react_1.useEffect)((()=>{const e=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting&&(l(!0),u.current&&(u.current.src=u.current.dataset.src||""),e.unobserve(t.target))}))}),{root:null,rootMargin:"0px",threshold:.5});return u.current&&e.observe(u.current),()=>{u.current&&e.unobserve(u.current)}}),[e]),(0,jsx_runtime_1.jsx)("img",{title:i,className:a,loading:"lazy",ref:u,"data-src":e,alt:t,width:r,height:s,style:{filter:o?"none":"blur(20px)",transition:"filter 0.9s"},id:n?.toString(),...c})};exports.default=ImageLazy;
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ const ImageLazy = ({ src, alt, width, height, className, id, extraData, title, }) => {
4
+ const imageRef = useRef(null);
5
+ const [isIntersecting, setIsIntersecting] = useState(false);
6
+ useEffect(() => {
7
+ const observer = new IntersectionObserver((entries) => {
8
+ entries.forEach((entry) => {
9
+ if (entry.isIntersecting) {
10
+ setIsIntersecting(true);
11
+ if (imageRef.current) {
12
+ imageRef.current.src = imageRef.current.dataset.src || "";
13
+ }
14
+ observer.unobserve(entry.target);
15
+ }
16
+ });
17
+ }, { root: null, rootMargin: "0px", threshold: 0.5 });
18
+ if (imageRef.current) {
19
+ observer.observe(imageRef.current);
20
+ }
21
+ return () => {
22
+ if (imageRef.current) {
23
+ observer.unobserve(imageRef.current);
24
+ }
25
+ };
26
+ }, [src]);
27
+ return (_jsx("img", { title: title, className: className, loading: "lazy", ref: imageRef, "data-src": src, alt: alt, width: width, height: height, style: {
28
+ filter: isIntersecting ? "none" : "blur(20px)",
29
+ transition: "filter 0.9s",
30
+ }, id: id?.toString(), ...extraData }));
31
+ };
32
+ export default ImageLazy;
@@ -0,0 +1 @@
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useRef,useState}from"react";const ImageLazy=({src:e,alt:t,width:r,height:s,className:a,id:n,extraData:c,title:i})=>{const o=useRef(null),[u,l]=useState(!1);return useEffect((()=>{const e=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting&&(l(!0),o.current&&(o.current.src=o.current.dataset.src||""),e.unobserve(t.target))}))}),{root:null,rootMargin:"0px",threshold:.5});return o.current&&e.observe(o.current),()=>{o.current&&e.unobserve(o.current)}}),[e]),_jsx("img",{title:i,className:a,loading:"lazy",ref:o,"data-src":e,alt:t,width:r,height:s,style:{filter:u?"none":"blur(20px)",transition:"filter 0.9s"},id:n?.toString(),...c})};export default ImageLazy;
@@ -0,0 +1,12 @@
1
+ type ImagesLazy = {
2
+ src: string;
3
+ alt: string;
4
+ width?: number;
5
+ height?: number;
6
+ id?: number | string;
7
+ className?: string;
8
+ title?: string;
9
+ extraData?: React.ImgHTMLAttributes<HTMLImageElement>;
10
+ };
11
+ declare const ImageLazy: ({ src, alt, width, height, className, id, extraData, title, }: ImagesLazy) => import("react/jsx-runtime").JSX.Element;
12
+ export default ImageLazy;
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "react-lazy-img-observer",
3
+ "version": "1.0.0",
4
+ "description": "A React component for lazy loading images with Intersection Observer",
5
+ "main": "dist/cjs/ImageLazy.min.js",
6
+ "module": "dist/esm/ImageLazy.min.js",
7
+ "types": "dist/types/ImageLazy.d.ts",
8
+ "scripts": {
9
+ "build": "tsc --project tsconfig.cjs.json && tsc --project tsconfig.esm.json && terser dist/cjs/ImageLazy.js -o dist/cjs/ImageLazy.min.js --compress --mangle && terser dist/esm/ImageLazy.js -o dist/esm/ImageLazy.min.js --compress --mangle"
10
+ },
11
+ "keywords": [
12
+ "react",
13
+ "lazy-load",
14
+ "image",
15
+ "intersection-observer"
16
+ ],
17
+ "author": "Percy Chuzon <contacto@percychuzon.com>",
18
+ "license": "ISC",
19
+ "homepage": "https://github.com/perch33/react-lazy-img-observer",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/perch33/react-lazy-img-observer.git"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/perch33/react-lazy-img-observer/issues"
26
+ },
27
+ "dependencies": {
28
+ "react": "^18.3.1",
29
+ "react-dom": "^18.3.1",
30
+ "terser": "^5.31.3"
31
+ },
32
+ "devDependencies": {
33
+ "@types/react": "^18.3.3",
34
+ "@types/react-dom": "^18.3.0",
35
+ "typescript": "^5.5.4"
36
+ }
37
+ }
@@ -0,0 +1,74 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ type ImagesLazy = {
4
+ src: string;
5
+ alt: string;
6
+ width?: number;
7
+ height?: number;
8
+ id?: number | string;
9
+ className?: string;
10
+ title?: string;
11
+ extraData?: React.ImgHTMLAttributes<HTMLImageElement>;
12
+ };
13
+
14
+ const ImageLazy = ({
15
+ src,
16
+ alt,
17
+ width,
18
+ height,
19
+ className,
20
+ id,
21
+ extraData,
22
+ title,
23
+ }: ImagesLazy) => {
24
+ const imageRef = useRef<HTMLImageElement>(null);
25
+ const [isIntersecting, setIsIntersecting] = useState<boolean>(false);
26
+
27
+ useEffect(() => {
28
+ const observer = new IntersectionObserver(
29
+ (entries) => {
30
+ entries.forEach((entry) => {
31
+ if (entry.isIntersecting) {
32
+ setIsIntersecting(true);
33
+ if (imageRef.current) {
34
+ imageRef.current.src = imageRef.current.dataset.src || "";
35
+ }
36
+ observer.unobserve(entry.target);
37
+ }
38
+ });
39
+ },
40
+ { root: null, rootMargin: "0px", threshold: 0.5 }
41
+ );
42
+
43
+ if (imageRef.current) {
44
+ observer.observe(imageRef.current);
45
+ }
46
+
47
+ return () => {
48
+ if (imageRef.current) {
49
+ observer.unobserve(imageRef.current);
50
+ }
51
+ };
52
+ }, [src]);
53
+
54
+ return (
55
+ <img
56
+ title={title}
57
+ className={className}
58
+ loading="lazy"
59
+ ref={imageRef}
60
+ data-src={src}
61
+ alt={alt}
62
+ width={width}
63
+ height={height}
64
+ style={{
65
+ filter: isIntersecting ? "none" : "blur(20px)",
66
+ transition: "filter 0.9s",
67
+ }}
68
+ id={id?.toString()}
69
+ {...extraData}
70
+ />
71
+ );
72
+ };
73
+
74
+ export default ImageLazy;
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "CommonJS",
5
+ "outDir": "dist/cjs"
6
+ }
7
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "ESNext",
5
+ "outDir": "dist/esm"
6
+ }
7
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "declaration": true,
6
+ "jsx": "react-jsx",
7
+ "declarationDir": "dist/types",
8
+ "removeComments": true,
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "outDir": "dist",
14
+ "moduleResolution": "node"
15
+
16
+ },
17
+ "include": ["src"],
18
+ "exclude": ["node_modules"]
19
+ }