DEV Community

Cover image for Client side pagination with React
Akinnagbe Oluwasegun
Akinnagbe Oluwasegun

Posted on

Client side pagination with React

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

Alt Text
...
Next we create some constants to help with the pagination and logic for the previous and next button, the constants are

  1. current page number
  2. number of items to show per page
  3. current page
  4. the paginated posts

it will look like this in code

  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 👇

Alt Text

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)

Collapse
 
devcoder profile image
devcoder

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

Collapse
 
maddealer profile image
maddealer

cool

Collapse
 
abhishekjain35 profile image
Abhishek Jain

That was great, thanks 😁😁

Collapse
 
vandathron profile image
Vandathron

Nice read. Thanks!