How to build a load more button with React

How to build a load more button with React

load more button in react

Here's a preview of what we'll be building.

Let's get into it.

Create a new react project using CRA

npx create-react-app loadmore

Get some sample posts.

  • Get them from here
  • Put these posts in a postsArray.js file and export them like below. posts exported from postsArray.js

Create a component to display posts

  • This component will accept a prop called postsToRender. We will pass this prop from our App component.
import React from "react";
const Posts = ({ postsToRender }) => {return (
    <ul>
      {postsToRender.map((post, index) => (
        <li key={index}>
          <strong>{post.id}</strong>
          &nbsp;{post.title}
        </li>
      ))}
    </ul>
  );
};
export default Posts;

App.js. The main bit!

I'll quickly run through what we'll be doing before showing the code. In App.js, import the posts from postsArray.js.

  • create a variable called postsPerPage for the number of additional posts to show each time the user clicks the load more button.
  • Declare a variable called arrayForHoldingPosts to hold the posts before we display them.
  • create a load more button and give it an onClick handler called handleShowMorePosts
  • create the handleShowMorePosts function that will run each time the load more button is clicked.

Now the code!

import React, { useState, useEffect } from "react";

import Posts from "./Posts";
import posts from "./postsArray";
const postsPerPage = 3;
let arrayForHoldingPosts = [];

const App = () => {
  const [postsToShow, setPostsToShow] = useState([]);
  const [next, setNext] = useState(3);

  const loopWithSlice = (start, end) => {
    const slicedPosts = posts.slice(start, end);
    arrayForHoldingPosts = [...arrayForHoldingPosts, ...slicedPosts];
    setPostsToShow(arrayForHoldingPosts);
  };

  useEffect(() => {
    loopWithSlice(0, postsPerPage);
  }, []);

  const handleShowMorePosts = () => {
    loopWithSlice(next, next + postsPerPage);
    setNext(next + postsPerPage);
  };

  return (
    <div>
      <Posts postsToRender={postsToShow} />
      <button onClick={handleShowMorePosts}>Load more</button>
    </div>
  );
};

export default App;

If you want to see the App.js code in a cleaner form, check out the github gist.