Hello guys here I'll be teaching you how to implement a client side pagination with React.
You don't have to put your application users through the boring experience of scrolling and more scrolling to see more content on your application, wouldn't it be nice to have a next or previous button to help with displaying more content? Well enough talk and let's get into the code.
This tutorial assumes you already know how to setup a project with create-react-app.
The first thing we'll do it create a component and make a request to join placeholder to get about 50 users to display, here is it in code.
import React from "react";
const Posts
= () => {
const [posts, setPosts]=useState([])
useEffect(()=>{
fetch('https://jsonplaceholder.typicode.com/posts?_limit=50')
.then(res => res.json())
.then(data=>{
setPosts(data)
})
})
return (
<div className='body'>
<h2 style={{textAlign:'center', marginBottom:'20px'}} >Paginations</h2>
{posts.map((post)=>(
<div key={post.id} style={{marginBottom:'20px'}} >
<h2>{post.title} </h2>
<p>{post.body} </p>
</div>
))}
</div>
);
};
This is how it looks like without pagination
...
Next we create some constants to help with the pagination and logic for the previous and next button, the constants are
- current page number
- number of items to show per page
- current page
- the paginated posts
it will look like this in code
javascript
const Posts = () => {
const [posts, setPosts]=useState([])
const [pageNumber, setPageNumber]= useState(1)
const [postNumber]= useState(5)
const currentPageNumber = (pageNumber * postNumber) - postNumber
const paginatedPosts = posts.splice(currentPageNumber, postNumber)
const handlePrev =()=>{
if(pageNumber === 1) return
setPageNumber(pageNumber - 1)
}
const handleNext =()=>{
setPageNumber(pageNumber + 1)
}
useEffect(()=>{
fetch('https://jsonplaceholder.typicode.com/posts?_limit=50')
.then(res => res.json())
.then(data=>{
setPosts(data)
})
})
return (
<div>
<h2>Posts</h2>
{paginatedPosts.map((post)=>(
<div key={post.id}>
<h2>{post.title} </h2>
<p>{post.body} </p>
</div>
))}
<div>Page {pageNumber} </div>
<div>
<button onClick={handlePrev} >prev</button>
<button onClick={handleNext}>next</button>
</div>
</div>
);
};
And now we have this 👇
That's it guys a simple pagination with React, this is my very first article and I'll be writing more on React and Javascript.
Have any thing you're struggling with about React or Javascript? You can send me a mail on theakinnagbe@gmail.com.
I'll do my best to help if I can. Cheers ❤❤
Top comments (4)
how would you handle this if you are not calling data from an API and just want to use the next and prev to go to different component routes? I have an SPA that has 5 seperate routes that each have their own page and would like to be able to click next or prev to get to them
cool
That was great, thanks 😁😁
Nice read. Thanks!