Skip to content

Instantly share code, notes, and snippets.

@onedebos

onedebos/App.jsx

Last active Jul 23, 2021
Embed
What would you like to do?
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;
@vinall

This comment has been minimized.

Copy link

@vinall vinall commented Aug 27, 2020

what is the implementation of postsArray ?

@onedebos

This comment has been minimized.

Copy link
Owner Author

@onedebos onedebos commented Aug 27, 2020

what is the implementation of postsArray ?

I'm not showing it here but it's shown in the tutorial itself.

postsArray.js is a file that holds and exports an array of post objects.

I.e you'll have something like

const posts = [
{id:1,...}
]

export default posts

@vinall

This comment has been minimized.

Copy link

@vinall vinall commented Aug 28, 2020

Cool.. Thanks this helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment