Client Side Pagination With React JS

Hello everyone, in this tutorial I’ll show you how to use React to construct client side pagination.

Wouldn’t it be great if your application had a next or previous button to help show additional content so that users wouldn’t have to go through the tiresome process of scrolling and further scrolling to see more content? I’ll stop now; let’s get to working with the code.

You should be familiar with the create-react-app project setup procedure before beginning this session.

Here is the code for the component we will initially develop and the request to join placeholder we will make to acquire roughly 50 users to display.

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>
    );
};

The last step is to add some constants to assist with the pagination and logic for the previous and next buttons.

  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>
    );
};

This is the way to simple validation with client side.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories