An awesome Infinite Scroll component in react.

Overview

react-infinite-scroll-component npm npm

All Contributors

A component to make all your infinite scrolling woes go away with just 4.15 kB! Pull Down to Refresh feature added. An infinite-scroll that actually works and super-simple to integrate!

Install

  npm install --save react-infinite-scroll-component

  or

  yarn add react-infinite-scroll-component

  // in code ES6
  import InfiniteScroll from 'react-infinite-scroll-component';
  // or commonjs
  var InfiniteScroll = require('react-infinite-scroll-component');

Using

<InfiniteScroll
  dataLength={items.length} //This is important field to render the next data
  next={fetchData}
  hasMore={true}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
  // below props only if you need pull down functionality
  refreshFunction={this.refresh}
  pullDownToRefresh
  pullDownToRefreshThreshold={50}
  pullDownToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
  }
  releaseToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
  }
>
  {items}
</InfiniteScroll>

Using scroll on top

<div
  id="scrollableDiv"
  style={{
    height: 300,
    overflow: 'auto',
    display: 'flex',
    flexDirection: 'column-reverse',
  }}
>
  {/*Put the scroll bar always on the bottom*/}
  <InfiniteScroll
    dataLength={this.state.items.length}
    next={this.fetchMoreData}
    style={{ display: 'flex', flexDirection: 'column-reverse' }} //To put endMessage and loader to the top.
    inverse={true} //
    hasMore={true}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {this.state.items.map((_, index) => (
      <div style={style} key={index}>
        div - #{index}
      </div>
    ))}
  </InfiniteScroll>
</div>

The InfiniteScroll component can be used in three ways.

  • Specify a value for the height prop if you want your scrollable content to have a specific height, providing scrollbars for scrolling your content and fetching more data.
  • If your scrollable content is being rendered within a parent element that is already providing overflow scrollbars, you can set the scrollableTarget prop to reference the DOM element and use it's scrollbars for fetching more data.
  • Without setting either the height or scrollableTarget props, the scroll will happen at document.body like Facebook's timeline scroll.

docs version wise

3.0.2

live examples

  • infinite scroll (never ending) example using react (body/window scroll)
    • Edit yk7637p62z
  • infinte scroll till 500 elements (body/window scroll)
    • Edit 439v8rmqm0
  • infinite scroll in an element (div of height 400px)
    • Edit w3w89k7x8
  • infinite scroll with scrollableTarget (a parent element which is scrollable)
    • Edit r7rp40n0zm

props

name type description
next function a function which must be called after reaching the bottom. It must trigger some sort of action which fetches the next data. The data is passed as children to the InfiniteScroll component and the data should contain previous items too. e.g. Initial data = [1, 2, 3] and then next load of data should be [1, 2, 3, 4, 5, 6].
hasMore boolean it tells the InfiniteScroll component on whether to call next function on reaching the bottom and shows an endMessage to the user
children node (list) the data items which you need to scroll.
dataLength number set the length of the data.This will unlock the subsequent calls to next.
loader node you can send a loader component to show while the component waits for the next load of data. e.g. <h3>Loading...</h3> or any fancy loader element
scrollThreshold number | string A threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down.
onScroll function a function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect.
endMessage node this message is shown to the user when he has seen all the records which means he's at the bottom and hasMore is false
className string add any custom class you want
style object any style which you want to override
height number optional, give only if you want to have a fixed height scrolling content
scrollableTarget node or string optional, reference to a (parent) DOM element that is already providing overflow scrollbars to the InfiniteScroll component. You should provide the id of the DOM node preferably.
hasChildren bool children is by default assumed to be of type array and it's length is used to determine if loader needs to be shown or not, if your children is not an array, specify this prop to tell if your items are 0 or more.
pullDownToRefresh bool to enable Pull Down to Refresh feature
pullDownToRefreshContent node any JSX that you want to show the user, default={<h3>Pull down to refresh</h3>}
releaseToRefreshContent node any JSX that you want to show the user, default={<h3>Release to refresh</h3>}
pullDownToRefreshThreshold number minimum distance the user needs to pull down to trigger the refresh, default=100px , a lower value may be needed to trigger the refresh depending your users browser.
refreshFunction function this function will be called, it should return the fresh data that you want to show the user
initialScrollY number set a scroll y position for the component to render with.
inverse bool set infinite scroll on top

Contributors

Thanks goes to these wonderful people (emoji key):


Ankeet Maini

💬 📖 💻 👀 🚧

Darsh Shah

🚇

This project follows the all-contributors specification. Contributions of any kind are welcome!

LICENSE

MIT

Issues
  • Is it possible to use `react-infinite-scroll-component` for scrolling UP?

    Is it possible to use `react-infinite-scroll-component` for scrolling UP?

    I need to have exactly the same behavior but for scrolling up also. Is it possible using this component?

    opened by olegkalyta 28
  • does not load the first page if not scrolling down

    does not load the first page if not scrolling down

    the next callback seems to be called only after a scroll down event. if the page isn't full and I cannot scroll down to the bottom (cause I already reached it), then the loader is displayed, but the next callback doesn't get called. this is obvious when you start the component with no children.

    opened by epifab 22
  • How can i use this component on mobile devices

    How can i use this component on mobile devices

    How can i use this component on mobile devices? When I use this component I can't scroll any element on the phone browsers

    help wanted 
    opened by mrTangYun 12
  • Add pull down to refresh as well?

    Add pull down to refresh as well?

    Great library that actually works! I realized no other React.js infinite scroll components support both pull down to refresh and pull up to load more, if this can be implemented as well, it could be make this library a killer!

    opened by kdenz 11
  • scrollableTarget not working

    scrollableTarget not working

    Hi, i was having trouble while using infinite scrolling, because data was being loaded when my browsers main window scrollbar scrolled. So i tried using scrollableTarget to fix the problem, but when i tried using it the loader keeps displaying and no data is fetched. Code looks like this:

    <Container id="divID">
            <InfiniteScroll
              dataLength={this.state.logs.length}
              next={this.fetchMoreData}
              hasMore={true}
              loader={<Loader />}
              scrollableTarget="divID"
            >
              <Table striped>
                <thead>
                  <tr>
                    <th>...</th>
                    <th>...</th>
                    <th>...</th>
                  </tr>
                </thead>
                <tbody>
                  {this.state.logs.map(event => (
                    <tr key={event.id}>
                      <td>....</td>
                      <td>....</td>
                      <td>....</td>
                    </tr>
                        ))}
                </tbody>
              </Table>
            </InfiniteScroll>
    </Container>
    

    Here you can see the id of Container screen shot 2018-05-28 at 00 25 05

    I Also tried using scrollableTarget=document.getElementById("divID") and it now renders the content but it only loads more data when the main window scrollbar moves not when the one in my Table element does.

    opened by lsvargas 11
  • componentWillReceiveProps has been renamed

    componentWillReceiveProps has been renamed

    • Move data fetching code or side effects to componentDidUpdate.
    • If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
    • Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

    Please update the following components: InfiniteScroll

    I get this warning in my console constantly. Am I using InfiniteScroll incorrectly or this legit something that needs to be addressed?

    opened by jaexplorer 11
  • Uncaught TypeError: Cannot read property 'style' of null

    Uncaught TypeError: Cannot read property 'style' of null

    get the error: Uncaught TypeError: Cannot read property 'style' of null, It is this line from the source code of index.js: _this._infScroll.style.overflow = 'auto';

    opened by szwork2013 9
  • Should this work in a functional component?

    Should this work in a functional component?

    I am trying to implement this in a functionali component, but it's not working. should it work or does it only work from class based component?

    opened by ElixirMike 8
  • scrollableTarget not trigger

    scrollableTarget not trigger

    Hi !! I am having some trouble with scrollableTarget prop. When I set the prop, the next function never gets triggered. It seems that I am doing something wrong but I can't see what ...

    Here is some part of my code:

    <Grid.Column width={11} id='billList' className='bill-content fdx-content bill-list-container'>
                  <InfiniteScroll
                    dataLength={this.props.bills.length} //This is important field to render the next data
                    next={this.loadBills}
                    scrollableTarget={document.getElementById('billList')}
                    onScroll={()=> {console.log(document.getElementById('billList'))}}
                    hasMore={this.state.hasMore}
                    loader={<Loader status={this.props.isFetching} />}
                    endMessage={
                      <p style={{textAlign: 'center'}}>
                        <b>Yay! You have seen it all</b>
                      </p>
                    }>
                      <BillList
                        localId={local.id}
                        token={token}
                        getBills={getBills}
                        openSidebar={this.openSidebar}
                        isSidebarOpen={isSidebarOpen}
                        bills={this.props.bills}
                      />
                    </InfiniteScroll>
                </Grid.Column>
    

    I have a 'Grid' parent div which has billList as ID. This means that the InfiniteScroll is not working with the div scroll. Besides, if I set a particular height to the InifniteScroll component the onScroll function logs all actions.

    I have also looked for some examples with the scrollableTarget option working, but it seems that there is any one in the repo.

    I hope you can help me !!

    Guido

    opened by gdpsysgarage 8
  • Expected a component class, got [object Object]

    Expected a component class, got [object Object]

    I do as shown in the example, but says it wants to component was

    <InfiniteScroll 
      pullDownToRefresh
      pullDownToRefreshContent={<h3 style={{textAlign: 'center'}}>&#8595; Pull down to refresh</h3>}
      releaseToRefreshContent={<h3 style={{textAlign: 'center'}}>&#8593; Release to refresh</h3>}
      refreshFunction={this.refresh}
      next={this.generateDivs}
      hasMore={true}
      loader={<h4>Loading...</h4>}>
      {[
        <div key={2} style={{height: 200, background: '#ffd47b'}}>Div no 2</div>,
        <div key={1} style={{height: 200, background: '#9bc95b'}}>Div no 1</div>,
        <div key={3} style={{height: 200, background: '#95a9d6'}}>Div no 3</div>,
        <div key={4} style={{height: 200, background: '#ffa8e1'}}>Div no 4</div>,
        <div key={5} style={{height: 200, background: '#9bc95b'}}>Div no 5</div>,
        <div key={6} style={{height: 200, background: '#ffd47b'}}>Div no 6</div>,
        <div key={7} style={{height: 200, background: '#95a9d6'}}>Div no 7</div>,
        <div key={8} style={{height: 200, background: '#ffa8e1'}}>Div no 8</div>,
      ]}
    </InfiniteScroll>
    

    img

    # I copied this example all exactly the same error

    https://github.com/ankeetmaini/react-infinite-scroll-component/blob/master/demos/height.js

    opened by bogdan8 8
  • Infinite scroll in both ways simultaneously?

    Infinite scroll in both ways simultaneously?

    How to make infinite scroll in both ways (top and bottom) at the same time? ex: When I reach top it loads data at top, when I reach bottom it loads data at bottom

    opened by MaxiFilippov 0
  • Bump url-parse from 1.4.7 to 1.5.3

    Bump url-parse from 1.4.7 to 1.5.3

    Bumps url-parse from 1.4.7 to 1.5.3.

    Commits
    • ad44493 [dist] 1.5.3
    • c798461 [fix] Fix host parsing for file URLs (#210)
    • 201034b [dist] 1.5.2
    • 2d9ac2c [fix] Sanitize only special URLs (#209)
    • fb128af [fix] Use 'null' as origin for non special URLs
    • fed6d9e [fix] Add a leading slash only if the URL is special
    • 94872e7 [fix] Do not incorrectly set the slashes property to true
    • 81ab967 [fix] Ignore slashes after the protocol for special URLs
    • ee22050 [ci] Use GitHub Actions
    • d2979b5 [fix] Special case the file: protocol (#204)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Question: is it possible to use this library with horizontal scrolling?

    Question: is it possible to use this library with horizontal scrolling?

    I use this library for infinite scrolling with vertical scrolling, which is quite common. I try to skim documentation and modify CSS but haven't found a solution. is it possible to have the scrolling horizontal?

    opened by kafinsalim 0
  • Images getting overlaped when scrolling in Mac Safari.

    Images getting overlaped when scrolling in Mac Safari.

    In case of safari, when i scroll the images are getting overlaped, can be seen in the GIF attached, working fine in case of Chrome, Firefox SafaroScrollissue

    opened by shivika24 0
  • scrollThreshold while zoom out

    scrollThreshold while zoom out

    I want to scroll all the way down to load more content and I set scrollThreshold={1} but it will stop after load some of the data while I zoom out a bit (80%). I works fine when I removed the threshold prop.

    opened by 5head-charles 0
  • Bump tmpl from 1.0.4 to 1.0.5

    Bump tmpl from 1.0.4 to 1.0.5

    Bumps tmpl from 1.0.4 to 1.0.5.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Add ability to style `outerdiv` inline and/or with className

    Add ability to style `outerdiv` inline and/or with className

    This will close https://github.com/ankeetmaini/react-infinite-scroll-component/issues/180

    I can't implement it locally (don't know how) but all tests passed and it looks good to me... the only problem might be conflicting overflow: ... inline styles on the outerdiv when this.props.pullDownToRefresh && this.props.height is true and someone also manually adds an overflow style. See:

    const outerDivStyle =
          this.props.pullDownToRefresh && this.props.height
            ? { overflow: 'auto', ...this.props.outerDivStyle }
            : { ...this.props.outerDivStyle };
    

    🤷‍♂️

    opened by benmneb 0
  • hasMore is false, service return the data = [] , so

    hasMore is false, service return the data = [] , so

    <InfiniteScroll hasMore={queryParams.hasMore} dataLength={productList.length} /> hasMore is false, service return the data = [] , so the len of productList not change, thus , refresh function not working

    opened by strawberry3269 0
  • Functions are not valid as a React child

    Functions are not valid as a React child

    Lib is working great, but i'am getting this error on console:

    Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

    Does anyone know how to getting rid of this error?

    Using:

    "next": "^11.0.0", "react": "^17.0.2", "styled-components": "^5.3.0",

    opened by rossignolli 0
Releases(v6.1.0)
React container that will auto scroll to bottom

react-scroll-to-bottom React container that will auto scroll to bottom or top if new content is added and viewport is at the bottom, similar to tail -

William Wong 99 Sep 17, 2021
Lazy load your component, image or anything matters the performance.

Note This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help. react-lazyload Lazyload your Componen

twobin 5.4k Oct 14, 2021
:scroll: A versatile infinite scroll React component.

ReactList A versatile infinite scroll React component. Install bower install react-list # or npm install react-list ReactList depends on React. Exam

Casey Foster 1.9k Oct 14, 2021
React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data. Check out the demo for some examples. Sponsors The following wonderful compan

Brian Vaughn 22.6k Oct 14, 2021
Simulate normal scrolling by using only fixed number of DOM elements for large lists of items with React Hooks

React Recycled Scrolling Simulate normal scrolling by using only fixed number of DOM elements for large lists of items with React Hooks Install npm in

sarons 24 Sep 2, 2021
react-sticky-scrollspy-nav is a React component that provides smooth scrolling navigation with sections to a web page.

react-sticky-scrollspy-nav react-sticky-scrollspy-nav is a React component that provides smooth scrolling navigation with sections to a web page. How

huurray 2 Oct 13, 2021