react-infinite-scroll-component load more with array

I made a semi-functioning example of what I think you are trying to do. Note that this plugin only seems to work if you can scroll. If your content is not tall enough to force scrolling then new content will never be able to load:

App.js

import React from "react";
import Scroll from "./Scroll";

const App = () => {
  const initialTweets = [
    { body: "Body 1" },
    { body: "Body 2" },
    { body: "Body 3" },
    { body: "Body 4" },
    { body: "Body 5" },
    { body: "Body 6" },
    { body: "Body 7" },
    { body: "Body 8" },
    { body: "Body 9" },
    { body: "Body 10" }
  ];

  return (
    <div>
      <h1>demo: react-infinite-scroll-component</h1>
      <hr />
      <Scroll tweets={initialTweets} />
    </div>
  );
};

export default App;

Scroll.jsx

import React, { useCallback, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

const Scroll = ({ tweets }) => {
  const [allTweets, setAllTweets] = useState(tweets);
  const [hasMore, setHasmore] = useState(true);
  const [lastPosition, setLastPosition] = useState(0);
  const perPage = 4;

  const loadProducts = useCallback(() => {
    setTimeout(() => {
      setAllTweets((prev) => [...prev, ...prev]);
    }, 2000);

    setLastPosition(lastPosition + perPage);
  }, []);

  console.log(allTweets);

  return (
    <InfiniteScroll
      dataLength={allTweets.length}
      next={loadProducts}
      hasMore={hasMore}
      loader={<h4>Loading...</h4>}
    >
      <div className="flex flex-col">
        {allTweets.map((value, index) => (
          <div key={index} className="py-10 px-5">
            {value.body}
          </div>
        ))}
      </div>
    </InfiniteScroll>
  );
};

export default Scroll;

You’ll need to tweak things to do exactly what you want, but this should point you in the right direction.

NOTE: To see this work in the codesandbox, either shrink the demo window so you can scroll or add a log more objects to the initialTweets array. Also, there are a number of examples you can find on the project’s homepage.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top