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:
- A React Project.
- useEffect and useState concepts.
- Good understanding on API requests.
- A working API endpoint that contains pagination.
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