npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@simbathesailor/react-infinite-scroll

v0.1.29

Published

A dead simple infinite-scroll react library

Downloads

33

Readme

react-infinite-scroll 📜

A dead simple React infinite-scroll

✅ Built on new flashy Reactjs hooks.

✅ No assumption on the how you bring data, just wrap the content inside the InfiniteScroll component

✅ Uses Intersection Observer API, hence performant than regular ways of doing it

✅ Completely configurable. Can be used to trigger infinite scroll in any direction.

✅ Takes care of screen resizing

✅ Tiny (1.4kb gzipped)

Installing

If using npm:


npm i @simbathesailor/react-infinite-scroll --save

If using yarn:


yarn add @simbathesailor/react-infinite-scroll

Demo

Demo App

Full Codesandbox Code

Usage

Scenario: When need to fetch new set of data when scroll end is reached

import { InfiniteScroll } from '@simbathesailor/react-infinite-scroll';

function App() {
  // setting up the active page fetched, It can be any logic needed

  const [activePageInfo, setActivePageInfo] = React.useState(1);

  // This is data recieved till now, which will be rendered.

  const [dataInfiniteScroll, setDataInfiniteScroll] = React.useState(null);

  // Logic to execute to get the initial set of results

  // On mount of the component , we are making an API call to get

  // the initial set of results.

  React.useEffect(() => {
    fetch(
      `https://5da9aa08de10b40014f3745c.mockapi.io/api/v1/feed?page=1&limit=10`
    )
      .then(res => {
        return res.json();
      })

      .then(data => {
        setDataInfiniteScroll(data);
      });
  }, []);

  // Logic to execute when the reached the end of the scroll

  // This is a callback which can be passed to InfiniteScroll component, The callback

  // will recieve the isVisible value as true when we reach the end of the scroll.

  const callbackForInfiniteScroll = React.useCallback(
    isVisible => {
      let activePage;

      setActivePageInfo(c => {
        activePage = c;

        return c;
      });

      if (isVisible) {
        fetch(
          `https://5da9aa08de10b40014f3745c.mockapi.io/api/v1/feed?page=${activePage +
            1}&limit=10`
        )
          .then(res => {
            return res.json();
          })

          .then(data => {
            setDataInfiniteScroll(dataInState => [...dataInState, ...data]);

            setActivePageInfo(c => c + 1);
          });
      }
    },

    [setActivePageInfo]
  );

  return (
    <div className="App">
      {/* Just need to pass the callback to invoke, when list reaches end */}

      <InfiniteScroll callback={callbackForInfiniteScroll}>
        {dataInfiniteScroll &&
          dataInfiniteScroll.map(elem => {
            /** Box is not a React element. It's a React component **/

            return <Box key={elem.id} {...elem} />;
          })}
      </InfiniteScroll>
    </div>
  );
}

// It is important to use forwardRef when Components are not React Elements.

// InfiniteScroll component takes the responsibility of initiliazing

// the intersection observer for you. ref should resolve to a DOM element

const Box = React.forwardRef((props, ref) => {
  const { avatar, id, name } = props;

  return (
    <div ref={ref} className="box-item">
      <img
        style={{ height: '60%', width: '60%', marginBottom: '10px' }}
        src={avatar}
        alt="no-avatar"
      />

      <span>{name}</span>
    </div>
  );
});

Scenario: When need to fetch new set of data with some offset at bottom of the page.

Let' see only the changed code from above. Infinite scroll takes rootMargin as one of the option similar to intersection observer API. Hence any offset can be given as:

rootMargin: "[topOffset], [rightOffset], [bottomOffset], [leftOffset]". Let's see the one of the example having a bottom offset of 680px.

<div className="App">
  <h1>Scroll to see Infinite scroll in action</h1>

  {/* Just need to pass the callback to invoke, when list reaches end */}

  <InfiniteScroll
    callback={callbackForInfiniteScroll}
    options={{
      rootMargin: `0px 0px 680px 0px`,
    }}
  >
    {dataInfiniteScroll &&
      dataInfiniteScroll.map(elem => {
        return <Box key={elem.id} {...elem} />;
      })}
  </InfiniteScroll>
</div>

We can also give , top offset, left offset and right offset. So Infinite scroll can be done in any direction. This also support infinite scrolls in scrollable areas apart from viewport. *Need to test more on that.

Props

| Props | IsMandatory | Type | Default | Description | | ------------------ | ----------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | callback | Yes | (isVisibile) => { // Logic to trigger // next set of data} | | A callback from consumer,which gets isVisible booleanas the argument. | | options | No | object | {rootMargin: '0px 0px 0px 0px'threshold: '0, 1'when: truevisibilityCondition: Function} | These are the almost same options,which we pass to intersectionObserverexcept threshold which is changed to string type.Done for avoiding extra check for arraycomparison. | | whenInfiniteScroll | No | boolean | true | The flag which can be used to stopinfinitescroll behaviour, when false.can be used to off when , data is nomore to be fetched. | | LoadMoreComponent | No | React.ReactElement | Loading More... | This is a ReactElement or React Componentwhich is shown when scroll reaches end |

Concept

react-infinite-scroll is using Intersection Observer API. Hence very performant and slick. We can pass almost same options we pass for setting up intersection observer. Here is the link for MDN Intersection observer. You can read about it and understand why it is performant.

The InfiniteScroll Component make use of useInfiniteScroll and useIntersectionObserver hook. React version above >16.8.6 can use this component for infinite scrolling.

Plan is to bundle useIntersectionObserver as a separate package later.

Work to do

  • TestCases.

  • Other examples

  • Update readme with all the props InfiniteScroll component takes as a table.

  • Example how to stop the infinite scroll and sending the custom components as Loader.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

simbathesailor

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Contributors

Thanks goes to these wonderful people (emoji key):