Skip to content

Instantly share code, notes, and snippets.

@ogorei
Forked from onedebos/App.jsx
Created May 24, 2021 15:33
Show Gist options
  • Save ogorei/eb90788d73f9671412500ef90e72253f to your computer and use it in GitHub Desktop.
Save ogorei/eb90788d73f9671412500ef90e72253f to your computer and use it in GitHub Desktop.
How to implement a load more button in React
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment