首页 > 其他分享 >react-lazy-load-image-component

react-lazy-load-image-component

时间:2024-04-02 11:59:30浏览次数:22  
标签:load lazy image component use react

react-lazy-load-image-component

DefinitelyTyped icon, indicating that this package has TypeScript declarations provided by the separate @types/react-lazy-load-image-component package 1.6.0 • Public • Published 10 months ago React Lazy Load Image Component Logo

React Lazy Load Image Component

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"

Build Status Dependency Status Download counter License

Live demo (code)

Features

  • Includes two components (LazyLoadImage and LazyLoadComponent) and a HOC (trackWindowScroll) which adds scroll position tracking to any component you wish.
  • Handles scroll events, resize events and re-renders that might change the position of the components. And, of course, above-the-fold on initial render.
  • Placeholder by default with the same size of the image/component.
  • A custom placeholder component or image can be specified.
  • Built-in on-visible effects (blur, black and white and opacity transitions).
  • threshold is set to 100px by default and can be modified.
  • beforeLoad and onLoad events.
  • debounce and throttle included by default and configurable.
  • Uses IntersectionObserver for browsers that support it.
  • Server Side Rendering (SSR) compatible.
  • TypeScript declarations hosted on DefinitelyTyped.

Installation

# Yarn
$ yarn add react-lazy-load-image-component

# NPM
$ npm i --save react-lazy-load-image-component

LazyLoadImage usage

import 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;

Props

PropTypeDefaultDescription
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

Using effects

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"
    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.

Screenshot of the blur effect

  • 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.

Screenshot of the black-and-white effect

  • opacity: renders a blank space and transitions to full opacity when the image is loaded.

Screenshot of the opacity effect

LazyLoadComponent usage

import 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;

Props

PropTypeDefaultDescription
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.

Using trackWindowScroll HOC to improve performance

When 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.

Props

LazyLoadImage

PropTypeDefaultDescription
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)

PropTypeDefaultDescription
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.

When to use 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);

Demos

Screenshot of the react-lazy-load-image-component in use

Common errors

All images are being loaded at once

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.

Effects are not working

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.

Warning: setState(...): Can only update a mounted or mounting component.

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.

Readme

Keywords

标签:load,lazy,image,component,use,react
From: https://www.cnblogs.com/sexintercourse/p/18110246

相关文章

  • 【雷达】测量聚变 React堆中等离子体的FMCW雷达和相关DSP模型matlab代码
     ✅作者简介:热爱科研的Matlab仿真开发者,修心和技术同步精进,代码获取、论文复现及科研仿真合作可私信。......
  • 3. dataset、dataloader
    dataset数据集dataloader数据加载器1.AI训练时的需求有一个数据集文件来,里面有100w的样本和标签训练时,通常希望,一次在100w中随机抓取batch个样本,拿去训练如果全部抓取完毕,则重新打乱后,再来一次2.dataset,数据集作用:储存数据集的信息self.xxx获取数据集长度__len_......
  • Pytorch - Dataloader
    BasicallytheDataLoaderworkswiththeDatasetobject.SotousetheDataLoaderyouneedtogetyourdataintothisDatasetwrapper.Todothisyouonlyneedtoimplementtwomagicmethods:__getitem__and__len__.The__getitem__takesanindexandretu......
  • 前端自动部署报错“http://registry.npm.taobao.org/****/download/array-tree-filter
    自动部署时报错我试过更改淘宝镜像为https://registry.npmmirror.com但都不生效报错如下图:代码中的配置文件如下如上配置在其他测试环境均正常,只在生产环境报错求大佬帮忙看看是什么原因呀......
  • react防抖节流
    防抖importReact,{useState,useEffect}from'react';constDebounceExample=()=>{const[inputValue,setInputValue]=useState('');useEffect(()=>{constdelay=1000;//设置防抖延迟时间为1秒consttimer=setTimeou......
  • 报错:react.development.js:1130 Uncaught Error: Objects are not valid as a React
      原因:是因为getControl我用了异步async的方法。而调用的时候,没有加上await导致的。 解决办法:加上await就可以了 ......
  • 使用React 18和WebSocket构建实时通信功能
    1.引言WebSocket是一种在Web应用中实现双向通信的协议。它允许服务器主动向客户端推送数据,而不需要客户端发起请求。在现代的实时应用中,WebSocket经常用于实时数据传输、聊天功能、实时通知和多人协作等场景。在本篇博客中,我们将探索如何在React18应用中使用WebSocket来......
  • 从虚拟dom知识无痛深入vue与react的原理
     我们都知道像vue、react都有用到虚拟dom,那么虚拟dom到底是什么?框架为什么不直接操作真实dom而要在中间要引入虚拟dom呢?vue和react的虚拟dom又有什么异同呢?我们就从虚拟dom开始讲起,再来逐步引入讲解vue与react的部分原理及其异同,这里会顺便讲解到数据驱动视图及视图驱动数据,......
  • React Native简介和环境配置,差点挂在第四面
    ReactNative目前需要NodeJS5.0或更高版本。本文发布时Homebrew默认安装的是最新版本,一般都满足要求。brewinstallnode安装完node后建议设置npm镜像以加速后面的过程(或使用科学上网工具)。注意:不要使用cnpm!cnpm安装的模块路径比较奇怪,packager不能正常识别!npmconfig......
  • react路径别名@配置
    首先下载包craconpmi-D @craco/craco1.路径解析在项目根目录下创建craco.config.js配置如下2.vscode识别配置在项目根目录下创建jsconfig.json,配置如下3. package.json将start和build的内容改成craco,重启项目 ......