Implementing Infinite Scroll Into a React Component

本文主要是介绍Implementing Infinite Scroll Into a React Component,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

In our face-paced modern society, who has time to click through pages and pages of content? “Not I,” said the web developer. In a world full of shortcuts, swipes and other gestures, the most efficient way to get through pages of content is the infinite scroll.

While not a new concept, the idea of infinite scroll is still somewhat controversial. Like most things, it has a time and a place in modern web design when properly implemented.

For anybody unfamiliar, infinite scroll is the concept of new content being loaded as you scroll down a page. When you get to the bottom of the content, the site automatically loads new content and appends it to the bottom.

Infinite scroll may not be ideal for all types of content, it is especially useful of feeds of data that an end-user would most probably want to page through quickly.

A perfect use case, and one you may already be familiar with is Instagram. You are presented with a feed of images and as you scroll down, more images keep showing up. Over and over and over until they run out of content to give you.

This article will teach you how to implement the infinite scroll concept into a React component and uses the Random User Generator to load a list of users from.

? Alligator.io recommends ⤵

⚛️ Fullstack Advanced React & GraphQL by Wes Bos

ⓘ About this affiliate link


Before we begin, we need to make sure we have the proper dependencies in our project. To load data from the Random User Generator we are going to use superagent.

For debouncing of the events (more on that in a bit), we’re going to use lodash:

To add superagent and lodash.debounce to your project via npm run:

$ npm install --save superagent lodash.debounce

Or via yarn:

$ yarn add superagent lodash.debounce

The crux of our infinite scroll component is going to be an onscroll event that will check to see if the user has scrolled to the bottom of the page. Upon reaching the bottom of the page, our event will attempt to load additional content.

When binding events, especially to scroll events, it’s good practice to debounce the events. Debouncing is when you only run a function once it a specified amount of time has passed since it was last called.

Debouncing improves performance for your user by limiting how often an event if fired and also helps take some strain off of any services you may be calling from the event handler.

window.onscroll = debounce(() => {if (window.innerHeight + document.documentElement.scrollTop=== document.documentElement.offsetHeight) {// Do awesome stuff like loading more content!}
}, 100);

The data that has been loaded will be appended to an array in the component’s state and will be iterated through in the component’s render method.

All good things come to an end. For demonstration purposes our component will eventually stop loading new content and display a message that it's reached the end and there is no additional content.


Now that we understand the logic flow that’s necessary to implement infinite scroll, let’s dive into our component:

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import request from "superagent";
import debounce from "lodash.debounce";class InfiniteUsers extends Component {constructor(props) {super(props);// Sets up our initial statethis.state = {error: false,hasMore: true,isLoading: false,users: [],};// Binds our scroll event handlerwindow.onscroll = debounce(() => {const {loadUsers,state: {error,isLoading,hasMore,},} = this;// Bails early if:// * there's an error// * it's already loading// * there's nothing left to loadif (error || isLoading || !hasMore) return;// Checks that the page has scrolled to the bottomif (window.innerHeight + document.documentElement.scrollTop=== document.documentElement.offsetHeight) {loadUsers();}}, 100);}componentWillMount() {// Loads some users on initial loadthis.loadUsers();}loadUsers = () => {this.setState({ isLoading: true }, () => {request.get('https://randomuser.me/api/?results=10').then((results) => {// Creates a massaged array of user dataconst nextUsers = results.body.results.map(user => ({email: user.email,name: Object.values(user.name).join(' '),photo: user.picture.medium,username: user.login.username,uuid: user.login.uuid,}));// Merges the next users into our existing usersthis.setState({// Note: Depending on the API you're using, this value may// be returned as part of the payload to indicate that there// is no additional data to be loadedhasMore: (this.state.users.length < 100),isLoading: false,users: [...this.state.users,...nextUsers,],});}).catch((err) => {this.setState({error: err.message,isLoading: false,});})});}render() {const {error,hasMore,isLoading,users,} = this.state;return (<div><h1>Infinite Users!</h1><p>Scroll down to load more!!</p>{users.map(user => (<Fragment key={user.username}><hr /><div style={{ display: 'flex' }}><imgalt={user.username}src={user.photo}style={{borderRadius: '50%',height: 72,marginRight: 20,width: 72,}}/><div><h2 style={{ marginTop: 0 }}>@{user.username}</h2><p>Name: {user.name}</p><p>Email: {user.email}</p></div></div></Fragment>))}<hr />{error &&<div style={{ color: '#900' }}>{error}</div>}{isLoading &&<div>Loading...</div>}{!hasMore &&<div>You did it! You reached the end!</div>}</div>);}
}const container = document.createElement("div");
document.body.appendChild(container);
render(<InfiniteUsers />, container);

There’s really not much to it!

The component manages a few status flags and list of data in it’s state, the onscroll event does most of the heavy lifting and the render method brings it to life on your screen!

We’re also making use of setState with a callback function passed-in as the second argument. The initial call to setState in our loadUsers method sets the value of loading to true and then in the callback function we load some users and call setState again to append our new users to the users already in the state.


I hope you’ve found this article on implementing infinite scroll in React informative.

If interested, you can find a working demo of this component over on CodeSandbox.

这篇关于Implementing Infinite Scroll Into a React Component的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/980746

相关文章

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2

CSS弹性布局常用设置方式

《CSS弹性布局常用设置方式》文章总结了CSS布局与样式的常用属性和技巧,包括视口单位、弹性盒子布局、浮动元素、背景和边框样式、文本和阴影效果、溢出隐藏、定位以及背景渐变等,通过这些技巧,可以实现复杂... 一、单位元素vm 1vm 为视口的1%vh 视口高的1%vmin 参照长边vmax 参照长边re

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加

css渐变色背景|<gradient示例详解

《css渐变色背景|<gradient示例详解》CSS渐变是一种从一种颜色平滑过渡到另一种颜色的效果,可以作为元素的背景,它包括线性渐变、径向渐变和锥形渐变,本文介绍css渐变色背景|<gradien... 使用渐变色作为背景可以直接将渐China编程变色用作元素的背景,可以看做是一种特殊的背景图片。(是作为背

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

css实现图片旋转功能

《css实现图片旋转功能》:本文主要介绍了四种CSS变换效果:图片旋转90度、水平翻转、垂直翻转,并附带了相应的代码示例,详细内容请阅读本文,希望能对你有所帮助... 一 css实现图片旋转90度.icon{ -moz-transform:rotate(-90deg); -webkit-transfo

vue基于ElementUI动态设置表格高度的3种方法

《vue基于ElementUI动态设置表格高度的3种方法》ElementUI+vue动态设置表格高度的几种方法,抛砖引玉,还有其它方法动态设置表格高度,大家可以开动脑筋... 方法一、css + js的形式这个方法需要在表格外层设置一个div,原理是将表格的高度设置成外层div的高度,所以外层的div需要

Vue项目中Element UI组件未注册的问题原因及解决方法

《Vue项目中ElementUI组件未注册的问题原因及解决方法》在Vue项目中使用ElementUI组件库时,开发者可能会遇到一些常见问题,例如组件未正确注册导致的警告或错误,本文将详细探讨这些问题... 目录引言一、问题背景1.1 错误信息分析1.2 问题原因二、解决方法2.1 全局引入 Element

详解如何在React中执行条件渲染

《详解如何在React中执行条件渲染》在现代Web开发中,React作为一种流行的JavaScript库,为开发者提供了一种高效构建用户界面的方式,条件渲染是React中的一个关键概念,本文将深入探讨... 目录引言什么是条件渲染?基础示例使用逻辑与运算符(&&)使用条件语句列表中的条件渲染总结引言在现代