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.
Create a component to display posts
- This component will accept a prop called
postsToRender
. We will pass this prop from ourApp
component.
import React from "react";
const Posts = ({ postsToRender }) => {return (
<ul>
{postsToRender.map((post, index) => (
<li key={index}>
<strong>{post.id}</strong>
{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 anonClick
handler calledhandleShowMorePosts
- 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.
Top comments (4)
I used this article to give me better guidance on this npm gallery package called Pro Gallery from WIx in React. They have a playground to test its settings & then generate the boilerplate code for it. But I'm trying to use their load more button & I just can't seem to grasp my head around how to pass get it to show more images. Maybe you can check it out & give some suggestions on how to use it. Thanks.
This is great! thanks Ade
I got this functionality to work but, when working in react, once I click away from the page with this function and comeback my data duplicates. How do i get it to refresh back to the original data?
to be clearer how do i get the state to refresh once I leave this screen and comback ?