Create pagination in React using Hooks.

Namrata Sanja
6 min readMay 3, 2021
Pagination

In this article, You will learn how to make pagination without node modules. Yes, there are lots of node modules are there for pagination like mdbreact, react-js-pagination and etc…

If react has already in-build components then why we need to write a code for pagination? this question comes in your mind. right?

Yes, obviously everyone has comes this question in their mind. Sometimes need to create a code functions for pagination like our data structure is different to pagination component needs data structure or some clients are ask that no need to use components or need pagination on div structure not in table structure at that time we need to create our own components for pagination.

So, Let’s start to learn how to create pagination.

Dashboard.js

let allDatas = [
{ name: “red”, colour: “red”},
{ name: “yellow”, colour: “yellow”},
{ name: “tomato”, colour: “tomato”},
{ name: “grey”, colour: “grey”},
{ name: “steelblue”, colour: “steelblue”},
{ name: “blueviolet”, colour: “blueviolet”},
{ name: “brown”, colour: “brown”},
{ name: “chocolate”, colour: “chocolate”},
{ name: “coral”, colour: “coral”},
{ name: “teal”, colour: “teal”}
];

This is all data array with name allDatas.

Create a new file for pagination with name of pagination.js

Note: always create new file for this type of common functionalities like pagination, slider and etc.

We are creating this file as a global. So, we can import it for another page. This components are called as a Reusable component.

Dashboard.js

<Pagination allData={allDatas}/>

We are importing Pagination component in Dashboard file and passing allData as a props in pagination.js like:

props.allData

We are using functional component. So, useEffect hook of pagination file is look like:

pagination.js

useEffect(() => { 
async function fetchData() {
if (props.allData) {
let data = [];
setAllDatas(props.allData);
props.allData.map((item, index) => {
if (index < NO_RECORDS) {
data.push(item);
}});
var total = isInt(props.allData.length, NO_RECORDS);
var totalpgs = total !== true ? parseInt(props.allData.length / NO_RECORDS) + 1 : props.allData.length / NO_RECORDS;
let pgs = [];
for (var i = 1; i <= Number(totalpgs); i++) {
pgs.push(i);
}
setTotalPage(pgs);
props.displayDatas(data);
}}
fetchData();
}, []);

This is UseEffect hook of pagination file. Let’s go in detail:

We need to keep condition at first, because sometimes data are getting after render components then array goes blank. So if added condition like if props.allData is coming then it will work correct. After that we are storing in one state like:

const [allDatas, setAllDatas] = useState([]);

then we are pushing number of data in array data. Need to declare constant for how many data need to display.

const NO_RECORDS = 2;

We are display 2 items per page. this hook is calling at first after page refresh only, So we call inital level. At very first time we an use this condition and push data in one variable:

if (index < NO_RECORDS) { 
data.push(item);
}

Now we are counting how many page need to display based on number of data.

For that, first need to check number of page is in int or float.

var total = isInt(props.allData.length, NO_RECORDS);

if result is in integer then page number is correct to diaplay but if not integer then we need to add one more page for display items:

var totalpgs = total !== true ? parseInt(props.allData.length / NO_RECORDS) + 1: props.allData.length / NO_RECORDS;

Now, looping in one array to display page numbers:

let pgs = [];
for (var i = 1; i <= Number(totalpgs); i++) {
pgs.push(i);
}
setTotalPage(pgs);

Now, we return result of items in dashboard file for display like:

props.displayDatas(data);

and in dashboard.js

<Pagination allData={allDatas} displayDatas={displayDatas} />

and create function with name of displayDatas:

const [pageDatas, setPageDatas] = useState([]);
const displayDatas = (data) => {
setPageDatas(data);
};

Now, display items are stored in pageDatas state. We are display items using map function:

{pageDatas.length > 0 && 
pageDatas.map((item, index) => {
return (
<div className="color_box" style={{ backgroundColor: item.colour }} >
<p>{item.name}</p>
</div>
);
})}

Yeah, inital things are done in pagination.

Now, we create pagination design in pagination.js like:

{totalPage.length > 0 && 
totalPage.map((item, index) => {
return (
<button type="button" key={index} title={item} className={`${currentPage === item ? "active" : ""} page_btn radial-out btn btn-primary`} onClick={() => activePageClick(item)} >
{item}
</button>
);
})}

Let’s create function activePageClick for change page:

const activePageClick = (page) => {
setCurrentPage(page);
var data = [];
allDatas.map((item, index) => {
if (index < page * NO_RECORDS && index >= (page - 1) * NO_RECORDS) {
data.push(item);
}});
props.displayDatas(data);
}

setCurrentPage state for display active page. also we are adding active class in button ${currentPage === item ? “active” : “”}.

for change items onChange of page need to change displayData which is in dashboard.js and we passing it from pagination.js using props like props.displayDatas(data);

Pagination with active page

Now let’s create functions and design for previous and next page buttons.

design:

{currentPage !== 1 && (
<button type="button" className={`page_btn radial-out btn btn-primary`} onClick={() => prevPage()} >
{"<"}
</button>
)}

Here is design of previous page button design. We are display this button obviously when we are not at first page. So first condition is for that.

function:

const prevPage = () => {
var page = currentPage - 1;
setCurrentPage(page);
var data = [];
allDatas.map((item, index) => {
if (index < page * NO_RECORDS && index >= (page - 1) * NO_RECORDS) {
data.push(item);
}});
props.displayDatas(data);
};

This function is almost same as active button click function. we need to go previous page for that we are doing minus 1 from currentPage.

Let’s create Next page Button. design and function are the same as previous. only chang is we are doing plus 1 from currentPage. Let’s see:

design:

{currentPage !== totalPage.length && (
<button type="button" className={`page_btn radial-out btn btn-primary`} onClick={() => nextPage()} >
{">"}
</button>
)

function:

const nextPage= () => {
var page = currentPage + 1;
setCurrentPage(page);
var data = [];
allDatas.map((item, index) => {
if (index < page * NO_RECORDS && index >= (page - 1) * NO_RECORDS) {
data.push(item);
}});
props.displayDatas(data);
};
Pagination with Previous and Next buttons

This is optional, to make extra in pagination we are creating two more buttons for go to direct first and last page.

Functions and designs are almost same as previos and next buttons. So why we are stop pagination from here.

So, Let’s start:

design for both buttons:

// Go to First Page
{currentPage !== 1 && (
<button type="button" className={`page_btn radial-out btn btn-primary`} onClick={() => firstPage()} >
{"<<"}
</button>
)
// Go to Last Page
{currentPage !== totalPage.length && (
<button type="button" className={`page_btn radial-out btn btn-primary`} onClick={() => lastPage()} >
{">>"}
</button>
)

Functions for both buttons:

// Go to First Page
const firstPage= () => {
var page = 1;
setCurrentPage(page);
var data = [];
allDatas.map((item, index) => {
if (index < page * NO_RECORDS && index >= (page - 1) * NO_RECORDS) {
data.push(item);
}});
props.displayDatas(data);
};
// Go to Last Page
const lastPage= () => {
var page = totalPage.length;
setCurrentPage(page);
var data = [];
allDatas.map((item, index) => {
if (index < page * NO_RECORDS && index >= (page - 1) * NO_RECORDS) {
data.push(item);
}});
props.displayDatas(data);
};

In functions only we need to change page numbers. Rest of the things are same for that 4 buttons.

Pagination is Done.

You can get full code from below URL of my GitHub Repo:

Hope, this article helps you to learn pagination and feels you how pagintion is easy in react.

If you have any question regarding pagination or any other things in React and Redux. Please comment below. For sure i will explain you.

Thanks for reading my article. Hope this help you to know react in a better way. Follow me to learn react and redux in better and easy way.

Happy coding … :)

--

--

Namrata Sanja

Web Developer. React, Redux (saga & thunk), Angular, React Native, Vuejs, gatsby, algolia, Antd, firebase