You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

react-infinite-scroll-hook

Package Overview
Dependencies
Maintainers
1
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-infinite-scroll-hook

A simple hook to create infinite scroll components

4.0.0
Source
npmnpm
Version published
Weekly downloads
116K
2.19%
Maintainers
1
Weekly downloads
 
Created
Source

react-infinite-scroll-hook

All Contributors

This is a hook to create infinite scroll components!
Live demo is here.

Before v4, useInfiniteScroll hook would basically check the DOM with an interval and look at the distance between the bottom of your "infinite" component and the bottom of the window. This was a simple solution. But it had its difficulties. It was not so easy to change the layout of your "infinite" component (like creating a chat message box with inverted scrolling etc). It was a requirement to modify the package based on each different use case.

And also, checking the DOM with an interval by using setInterval wasn't a sophisticated solution. It was enough, but it had it's limits. With v4, we migrated to use IntersectionObserver and created a much more flexible API to support different design. Basically, now we have a little bit more inversion of control.

Basically, we need to set a sentry component to trigger infinite loading. When sentry becomes visible on the screen, or it comes near (based on our config of course), it triggers infinite loading all with the help of IntersectionObserver. So, we can make components with different layouts like an inverted scrolling chat message box, horizontal scrolling etc.

Note: This package uses IntersectionObserver under the hood. You might want to check the browser compatibility from here and if you want to support older browsers, you might need to use a polyfill.

If you want to use the older version which is using setInterval, you can find it here.

Installation

npm install react-infinite-scroll-hook

Simple Example

import useInfiniteScroll from 'react-infinite-scroll-hook';

function SimpleInfiniteList() {
  const { loading, items, hasNextPage, error, loadMore } = useLoadItems();

  const [infiniteRef] = useInfiniteScroll({
    loading,
    hasNextPage,
    onLoadMore: loadMore,
    // When there is an error, we stop infinite loading.
    // It can be reactivated by setting "error" state as undefined.
    disabled: !!error,
    // `rootMargin` is passed to `IntersectionObserver`.
    // We can use it to trigger 'onLoadMore' when the sentry comes near to become
    // visible, instead of becoming fully visible on the screen.
    rootMargin: '0px 0px 400px 0px',
  });

  return (
    <List>
      {items.map((item) => (
        <ListItem key={item.key}>{item.value}</ListItem>
      ))}
      {/* 
          As long as we have a "next page", we show "Loading" right under the list.
          When it becomes visible on the screen, or it comes near, it triggers 'onLoadMore'.
          This is our "sentry".
          We can also use another "sentry" which is separated from the "Loading" component like:
            <div ref={infiniteRef} />
            {loading && <ListItem>Loading...</ListItem>}
          and leave "Loading" without this ref.
      */}
      {hasNextPage && (
        <ListItem ref={infiniteRef}>
          <Loading />
        </ListItem>
      )}
    </List>
  );
}

Or if we have a scrollable container and we want to use it as our "list container" instead of document, we just need to use rootRef like:

function InfiniteListWithVerticalScroll() {
  const { loading, items, hasNextPage, error, loadMore } = useLoadItems();

  const [infiniteRef, { rootRef }] = useInfiniteScroll({
    loading,
    hasNextPage,
    onLoadMore: loadMore,
    disabled: !!error,
    rootMargin: '0px 0px 400px 0px',
  });

  return (
    <ListContainer
      // This where we set our scrollable root component.
      ref={rootRef}
    >
      <List>
        {items.map((item) => (
          <ListItem key={item.key}>{item.value}</ListItem>
        ))}
        {hasNextPage && (
          <ListItem ref={infiniteRef}>
            <Loading />
          </ListItem>
        )}
      </List>
    </ListContainer>
  );
}

Other Examples

You can find different layout examples here. Live demo contains all of these cases.

Arguments

NameDescriptionTypeOptionalDefault Value
loadingSome sort of "is fetching" info of the request.boolean
hasNextPageIf the list has more items to load.boolean
onLoadMoreThe callback function to execute when the 'onLoadMore' is triggered.VoidFunction
rootMarginWe pass this to 'IntersectionObserver'. We can use it to configure when to trigger 'onLoadMore'.string
disabledFlag to stop infinite scrolling. Can be used in case of an error etc too.boolean
delayInMsHow long it should wait before triggering 'onLoadMore'.number100

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Eugene Fidelin

💻

Evan Cater

📖

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

Keywords

react

FAQs

Package last updated on 04 Apr 2021

Did you know?

Socket

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.

Install

Related posts