ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

How To Add Pagination On React App

How To Add Pagination On React App
How To Add Pagination On React App

In this tutorial, we will be discussing on how to add pagination on a react app. Pagination means to separate the contents into several pages. While developing a React app, we often need to render large amount of items from the api. so, to render those items within a certain limit in each page we use pagination.

Before we begin, make sure that you have:

An API endpoint with pagination looks something like:

`${API_endpoint}?page=${page}&limit=10`

Here, we need to pass the dynamic page number and recall the api request so that the contents on the new page gets rendered. So, to set the page numbers, we can set buttons for previous and next page whose onClick sets the page number according to the button click. We can set the value of page in the state using useState.

We need to recall the api as soon the the page changes so for that page changes. We can use useEffect hooks for that.

import axios from 'axios'
import React , {useState , useEffect} from 'react'

function Tutorial() {
    const [page , setPage] = useState(1);

    const fetchData = () => {
        const response = await axios.get(`${API_endpoint}?page=${page}&limit=10`)
        // response handling code goes here... 
    }

    useEffect(()=>{
        fetchData();
    },[page]);

  return (
    <div>
        {/* your contents rendering code goes here...  */}
         
         {/* pagination  */}
         <button className='btn btn-primary' onClick={()=>setPage(page - 1)}>Previous</button>
            <span className='p-2'>{page}</span>
         <button className='btn btn-primary' onClick={()=>setPage(page + 1)}>Next</button>
    </div>
  )
}

export default Tutorial
Sign up for daily dose of tech articles at your inbox.
Loading