Я использую компонент react-infinite-scroll-component с моим приложением Photo Viewer react.js. Git-репозиторий этого компонента: https://github.com/ankeetmaini/react-infinite-scroll-component.
Установка react-infinite-scroll-component в ваш проект:
npm i react-infinite-scroll-component
Я использую бесконечную прокрутку в компоненте Photo.js
import React, { useState } from "react"; import InfiniteScroll from "react-infinite-scroll-component"; const Photos = props => { const{photos, dimensions, pages, currentPage} = props const handleChange = (event) => { setValue(event.target.value); props.filterHendler(event.target.value) } return ( <div> {photos ? <InfiniteScroll dataLength={photos.length} next={props.fetchMoreData} hasMore={pages-currentPage!==0} loader={<h4>Loading...</h4>} > <div className='flex'> {photos.map((photo,index) => { return <div key={index}><img id={photo.id} src={photo.url} onClick={() => props.imageHendler(photo)}/></div>})} </div> </InfiniteScroll> : null} </div> )} export default Photos;
Затем рендерим фото в компоненте App.js
import React from 'react'; import './App.css'; import Photos from './Components/Photos' class App extends React.Component { state={ photos: null, pages: null, currentPage: null, } componentDidMount(){ fetch('https//localhost:3000/photos?page=1') .then(res => res.json()) .then(res => { this.setState({ photos: res.photos, pages: res.pages, currentPage: res.currentPage })}) } fetchMoreData=()=>{ if(this.state.currentPage-this.state.pages!==0){ fetch(`http://localhost:3000/photos?page=${this.state.currentPage + 1}`) .then(res => res.json()) .then(res => { this.setState({ photos: [...this.state.photos,...res.photos], pages: res.pages, currentPage: res.currentPage, }) })} } render(){ return ( <Photos fetchMoreData={this.fetchMoreData} photos={this.state.photos} pages={this.state.pages} currentPage={this.state.currentPage} />} /> )} }
Ресурсы: