Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
react-lazy-load-image-component
Advanced tools
React Component to lazy load images using a HOC to track window scroll position.
The react-lazy-load-image-component package is a React component that provides lazy loading functionality for images. It helps improve performance by loading images only when they are in the viewport, reducing the initial load time and bandwidth usage.
Basic Lazy Loading
This feature allows you to lazy load an image with a blur effect. The image will only load when it comes into the viewport, improving performance.
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
const App = () => (
<LazyLoadImage
alt={'Image Alt Text'}
height={200}
src={'https://example.com/image.jpg'} // use normal <img> attributes as props
width={200}
effect='blur'
/>
);
Placeholder Image
This feature allows you to specify a placeholder image that will be displayed while the main image is loading. This can enhance the user experience by providing a visual cue that an image is being loaded.
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
const App = () => (
<LazyLoadImage
alt={'Image Alt Text'}
height={200}
src={'https://example.com/image.jpg'}
width={200}
placeholderSrc={'https://example.com/placeholder.jpg'}
effect='blur'
/>
);
Custom Placeholder
This feature allows you to use a custom React component as a placeholder while the main image is loading. This provides more flexibility in designing the loading state.
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
const App = () => (
<LazyLoadImage
alt={'Image Alt Text'}
height={200}
src={'https://example.com/image.jpg'}
width={200}
placeholder={<div style={{ height: 200, width: 200, backgroundColor: '#ccc' }}>Loading...</div>}
effect='blur'
/>
);
react-lazyload is another popular package for lazy loading components and images in React. It provides a higher-order component and a hook for lazy loading, and it supports features like debounce and throttle. Compared to react-lazy-load-image-component, it offers more general-purpose lazy loading capabilities but may require more setup for image-specific use cases.
react-intersection-observer is a React implementation of the Intersection Observer API, which can be used to lazy load images and other components. It provides a hook and a render prop for observing when elements enter or leave the viewport. This package is more flexible and can be used for a variety of lazy loading scenarios, but it requires more manual setup for image-specific use cases compared to react-lazy-load-image-component.
react-lazy-load is a simple React component for lazy loading images and other components. It provides basic lazy loading functionality with minimal configuration. While it is easy to use, it lacks some of the advanced features like custom placeholders and effects that react-lazy-load-image-component offers.
React Component to lazy load images and other components/elements. Supports IntersectionObserver and includes a HOC to track window scroll position to improve performance.
"An easy-to-use performant solution to lazy load images in React"
LazyLoadImage
and LazyLoadComponent
) and a HOC (trackWindowScroll
) which adds scroll position tracking to any component you wish.beforeLoad
and onLoad
events.debounce
and throttle
included by default and configurable.We built several examples and components on top of react-lazy-load-image-component to safe you time. Check them out on LazyPixels.com.
# Yarn
$ yarn add react-lazy-load-image-component
# NPM
$ npm i --save react-lazy-load-image-component
LazyLoadImage
usageimport React from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';
const MyImage = ({ image }) => (
<div>
<LazyLoadImage
alt={image.alt}
height={image.height}
src={image.src} // use normal <img> attributes as props
width={image.width} />
<span>{image.caption}</span>
</div>
);
export default MyImage;
Prop | Type | Default | Description |
---|---|---|---|
onLoad | Function | Function called when the image has been loaded. This is the same function as the onLoad of an <img> which contains an event object. | |
afterLoad | Function | Deprecated, use onLoad instead. This prop is only for backward compatibility. | |
beforeLoad | Function | Function called right before the placeholder is replaced with the image element. | |
delayMethod | String | throttle | Method from lodash to use to delay the scroll/resize events. It can be throttle or debounce . |
delayTime | Number | 300 | Time in ms sent to the delayMethod. |
effect | String | Name of the effect to use. Please, read next section with an explanation on how to use them. | |
placeholder | ReactClass | <span> | React element to use as a placeholder. |
placeholderSrc | String | Image src to display while the image is not visible or loaded. | |
threshold | Number | 100 | Threshold in pixels. So the image starts loading before it appears in the viewport. |
useIntersectionObserver | Boolean | true | Whether to use browser's IntersectionObserver when available. |
visibleByDefault | Boolean | false | Whether the image must be visible from the beginning. |
wrapperClassName | String | In some occasions (for example, when using a placeholderSrc) a wrapper span tag is rendered. This prop allows setting a class to that element. | |
wrapperProps | Object | null | Props that should be passed to the wrapper span when it is rendered (for example, when using placeholderSrc or effect) |
... | Any other image attribute |
LazyLoadImage
includes several effects ready to be used, they are useful to add visual candy to your application, but are completely optional in case you don't need them or want to implement you own effect.
They rely on CSS and the corresponding CSS file must be imported:
import React from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
const MyImage = ({ image }) => (
<LazyLoadImage
alt={image.alt}
effect="blur"
wrapperProps={{
// If you need to, you can tweak the effect transition using the wrapper style.
style: {transitionDelay: "1s"},
}}
src={image.src} />
);
The current available effects are:
blur
: renders a blurred image based on placeholderSrc
and transitions to a non-blurred one when the image specified in the src is loaded.black-and-white
: renders a black and white image based on placeholderSrc
and transitions to a colorful image when the image specified in the src is loaded.opacity
: renders a blank space and transitions to full opacity when the image is loaded.All the effects have a transition duration of 0.3 seconds by default, without transition delay and the default transition timing function. All those values can be modified overriding the wrapper style as shown in the code example above.
LazyLoadComponent
usageimport React from 'react';
import { LazyLoadComponent } from 'react-lazy-load-image-component';
import { ArticleContent, ArticleComments } from 'my-app';
const Article = ({ articleId }) => (
<div>
<ArticleContent id={articleId} />
<LazyLoadComponent>
<ArticleComments id={articleId} />
</LazyLoadComponent>
</div>
);
export default Article;
Prop | Type | Default | Description |
---|---|---|---|
afterLoad | Function | Function called after the component has been rendered. | |
beforeLoad | Function | Function called right before the component is rendered. | |
delayMethod | String | throttle | Method from lodash to use to delay the scroll/resize events. It can be throttle or debounce . |
delayTime | Number | 300 | Time in ms sent to the delayMethod from lodash. |
placeholder | ReactClass | <span> | React element to use as a placeholder. |
threshold | Number | 100 | Threshold in pixels. So the component starts loading before it appears in the viewport. |
useIntersectionObserver | Boolean | true | Whether to use browser's IntersectionObserver when available. |
visibleByDefault | Boolean | false | Whether the component must be visible from the beginning. |
trackWindowScroll
HOC to improve performanceWhen you have many elements to lazy load in the same page, you might get poor performance because each one is listening to the scroll/resize events. In that case, it's better to wrap the deepest common parent of those components with a HOC to track those events (trackWindowScroll
).
For example, if we have an App
which renders a Gallery
, we would wrap the Gallery
component with the HOC.
import React from 'react';
import { LazyLoadImage, trackWindowScroll }
from 'react-lazy-load-image-component';
const Gallery = ({ images, scrollPosition }) => (
<div>
{images.map((image) =>
<LazyLoadImage
key={image.key}
alt={image.alt}
height={image.height}
// Make sure to pass down the scrollPosition,
// this will be used by the component to know
// whether it must track the scroll position or not
scrollPosition={scrollPosition}
src={image.src}
width={image.width} />
)}
</div>
);
// Wrap Gallery with trackWindowScroll HOC so it receives
// a scrollPosition prop to pass down to the images
export default trackWindowScroll(Gallery);
You must set the prop scrollPosition
to the lazy load components. This way, they will know the scroll/resize events are tracked by a parent component and will not subscribe to them.
LazyLoadImage
Prop | Type | Default | Description |
---|---|---|---|
scrollPosition | Object | Object containing x and y with the curent window scroll position. Required. | |
onLoad | Function | Function called when the image has been loaded. This is the same function as the onLoad of an <img> which contains an event object. | |
afterLoad | Function | Deprecated, use onLoad instead. This prop is only for backward compatibility. | |
beforeLoad | Function | Function called right before the image is rendered. | |
placeholder | ReactClass | <span> | React element to use as a placeholder. |
threshold | Number | 100 | Threshold in pixels. So the image starts loading before it appears in the viewport. |
visibleByDefault | Boolean | false | Whether the image must be visible from the beginning. |
wrapperProps | Object | null | Props that should be passed to the wrapper span when it is rendered (for example, when using placeholderSrc or effect) |
... | Any other image attribute |
Component wrapped with trackWindowScroll
(in the example, Gallery
)
Prop | Type | Default | Description |
---|---|---|---|
delayMethod | String | throttle | Method from lodash to use to delay the scroll/resize events. It can be throttle or debounce . |
delayTime | Number | 300 | Time in ms sent to the delayMethod from lodash. |
useIntersectionObserver | Boolean | true | Whether to use browser's IntersectionObserver when available. |
Notice you can do the same replacing LazyLoadImage
with LazyLoadComponent
.
visibleByDefault
?The prop visibleByDefault
makes the LazyLoadImage to behave like a normal <img>
. Why is it useful, then?
Imagine you are going to lazy-load an image you have already loaded in the same page. In that case, there is no need to lazy-load it because it's already stored in the cache of the user's browser. You can directly display it.
Maybe the following code snippet will make it more clear:
import React from 'react';
import { LazyLoadImage, trackWindowScroll }
from 'react-lazy-load-image-component';
const Gallery = ({ images, scrollPosition }) => (
<div>
// We are loading landscape.jpg here
<img src="/landscape.jpg" alt="Beautiful landscape" />
{images.map((image) =>
<LazyLoadImage
key={image.key}
alt={image.alt}
scrollPosition={scrollPosition}
src={image.src}
// If the image we are creating here has the same src than before,
// we can directly display it with no need to lazy-load.
visibleByDefault={image.src === '/landscape.jpg'} />
)}
</div>
);
export default trackWindowScroll(Gallery);
This package loads images when they are visible in the viewport. Before an image is loaded, it occupies 0x0 pixels, so if you have a gallery of images, that means all images will be in the visible part of the page until the first ones load and start pushing down the other ones.
To fix this issue, make sure you either set a height
and width
props or a placeholder
to your images.
You need to import the effect CSS as shown in the Using effects code example.
Also, notice browsers might behave differently while images are loading. Some times, while an image is not completely loaded yet, the browser will show a white background behind it, making the effect not to be visible. This is an issue with browsers and not something that can be fixed in this package.
That warning might appear if there are two components using trackWindowScroll
at the same time. Notice it's not possible to have a LazyLoadImage/LazyLoadComponent inside another LazyLoadComponent for now. Also, make sure you are passing down scrollPosition
to all components wrapped inside trackWindowScroll
.
FAQs
React Component to lazy load images using a HOC to track window scroll position.
The npm package react-lazy-load-image-component receives a total of 132,174 weekly downloads. As such, react-lazy-load-image-component popularity was classified as popular.
We found that react-lazy-load-image-component demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.