Giter Site home page Giter Site logo

kotarella1110 / use-simple-infinite-scroll Goto Github PK

View Code? Open in Web Editor NEW
19.0 2.0 0.0 2.36 MB

A simple React Hook for infinite scrolling built on the Intersection Observer API

Home Page: https://www.npmjs.com/package/use-simple-infinite-scroll

License: MIT License

TypeScript 100.00%
react react-hooks typescript infinite-scroll infinite scroll

use-simple-infinite-scroll's Introduction

use-simple-infinite-scroll

A simple React Hook for infinite scrolling built on the Intersection Observer API

License Actions Status NPM Version Downloads Month Downloads Total Dependencies Status Semantic Release Commitizen Friendly PRs Welcome

All Contributors

Installation

npm install use-simple-infinite-scroll

Usage

Edit kotarella1110/use-simple-infinite-scroll: example

Basic

import React, { useState } from 'react';
import { useSimpleInfiniteScroll } from 'use-simple-infinite-scroll';

type Item = {
  id: number;
  name: string;
};

type Result = {
  data: Item[];
  nextCursor: number | null;
};

const canFetchMore = (nextCursor: Result['nextCursor']) => nextCursor !== null;

const InfiniteScrollExample = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [items, setItems] = useState<Item[]>([]);
  const [nextCursor, setNextCursor] = useState<Result['nextCursor']>(0);

  const fetchMore = () => {
    setIsLoading(true);
    fetch(`/api/items?cursor=${nextCursor}`)
      .then((res) => res.json())
      .then((res: Result) => {
        setItems([...items, ...res.data]);
        setNextCursor(res.nextCursor);
        setIsLoading(false);
      });
  };

  const [targetRef] = useSimpleInfiniteScroll({
    onLoadMore: fetchMore,
    canLoadMore: canFetchMore(nextCursor),
  });

  return (
    <>
      {items.length !== 0 ? (
        <ul>
          {items.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : null}
      <div ref={targetRef}>
        {isLoading
          ? 'Loading more...'
          : canFetchMore(nextCursor)
          ? 'Load More'
          : 'Nothing more to load'}
      </div>
    </>
  );
};

React Query

import React from 'react';
import { useInfiniteQuery } from 'react-query';
import { useSimpleInfiniteScroll } from 'use-simple-infinite-scroll';

type Item = {
  id: number;
  name: string;
};

type Result = {
  data: Item[];
  nextCursor: number | null;
};

const InfiniteScrollExample = () => {
  const {
    status,
    data,
    error,
    isFetching,
    isFetchingMore,
    fetchMore,
    canFetchMore,
  } = useInfiniteQuery<Result, Error>(
    'items',
    (key: string, cursor = 0) =>
      fetch(`/api/items?cursor=${cursor}`).then((res) => res.json()),
    {
      getFetchMore: (lastGroup) => lastGroup.nextCursor,
    },
  );

  const [targetRef, rootRef] = useSimpleInfiniteScroll({
    onLoadMore: fetchMore,
    canLoadMore: !!canFetchMore,
  });

  return status === 'loading' ? (
    <p>Loading...</p>
  ) : status === 'error' ? (
    <span>Error: {error && error.message}</span>
  ) : (
    <div
      style={{
        overflow: 'auto',
      }}
      ref={rootRef}
    >
      <ul>
        {data &&
          data.map((page, i) => (
            <React.Fragment key={i}>
              {page.data.map((item) => (
                <li key={itme.id}>{item.name}</li>
              ))}
            </React.Fragment>
          ))}
      </ul>
      <div>
        <button
          type="button"
          ref={targetRef}
          onClick={() => fetchMore()}
          disabled={!canFetchMore || !!isFetchingMore}
        >
          {isFetchingMore
            ? 'Loading more...'
            : canFetchMore
            ? 'Load More'
            : 'Nothing more to load'}
        </button>
      </div>
      <div>
        {isFetching && !isFetchingMore ? 'Background Updating...' : null}
      </div>
    </div>
  );
};

API

const useSimpleInfiniteScroll: (options: {
  canLoadMore: boolean;
  onLoadMore: () => void;
  rootMargin?: string;
  threshold?: number | number[];
}) => [(target: Element | null) => void, (root: Element | null) => void];
Name Type Default Required Descripttion
canLoadMore boolean βœ“ Specifies if there are more entities to load.
onLoadMore () => void βœ“ Called when the user has scrolled all the way to the end.
rootMargin string "0px" Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left).
threshold number | number[] 0 Either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed.

For more information on rootMargin and threshold option, visit the MDN web docs.

FAQ

How can I assign multiple refs to a component?

You can wrap multiple ref assignments in a single useCallback:

import React, { useRef, useCallback } from 'react';
import { useSimpleInfiniteScroll } from 'use-simple-infinite-scroll';

const AssignMultipleRefsExample = () => {
  const rootRef = useRef<HTMLDivElement | null>();
  const targetRef = useRef<HTMLDivElement | null>();

  const [setTargetRef, setRootRef] = useSimpleInfiniteScroll({
    onLoadMore: () => {},
    canLoadMore: true,
  });

  // Use `useCallback` so we don't recreate the function on each render - Otherwise, the function passed to `onLoadMore` option will be called twice
  const setRootRefs = useCallback(
    (node: HTMLDivElement | null) => {
      // Ref's from useRef needs to have the node assigned to `current`
      rootRef.current = node;
      // Callback refs, like the one from `useSimpleInfiniteScroll`, is a function that takes the node as an argument
      setRootRef(node);
    },
    [setRootRef],
  );

  const setTargetRefs = useCallback(
    (node: HTMLDivElement | null) => {
      targetRef.current = node;
      setTargetRef(node);
    },
    [setTargetRef],
  );

  return (
    <div ref={setRootRefs}>
      <div ref={setTargetRefs} />
    </div>
  );
};

Which browsers are supported?

use-simple-infinite-scroll supports all of the major modern browsers. Browsers like IE11 are not supported: if you need to support older browsers you can add IntersectionObserver polyfill.

You can install the polyfill via npm or by downloading a zip of this repository:

npm install intersection-observer

Then import it in your app:

import 'intersection-observer';

Contributing

Contributions are always welcome! Please read the contributing first.

Contributors

Thanks goes to these wonderful people (emoji key):


Kotaro Sugawara

πŸ’» πŸ“– πŸ€” πŸš‡ ⚠️

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

License

MIT Β© Kotaro Sugawara

use-simple-infinite-scroll's People

Contributors

dependabot-preview[bot] avatar kotarella1110 avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

use-simple-infinite-scroll's Issues

react 17.0

Hello, I want to try the library but npm cannot resolve the dependency for react, can you update to the latest deps? Thanks!

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.