Build a Custom Pagination Component in ReactJS from Scratch
Hello there👋,
Setting Up The Project And Pagination Component
Let’s start by creating the react-app using following command,
npx create-react-app react-pagination-component
Create a separate file called PaginationComponent.js
. Here, We will use jsonplaceholder API to get data and use pagination on that data. This API will return us a list of todos. Now to store this data let’s create one state and initialize it with an empty array.
const [data, setData] = useState([]);
Now let’s use useEffect
to set this state with our data which comes from API.
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((response) => response.json())
.then((json) => setData(json));
}, []);
if you want to see what type of data this api is providing then just go to this url:API. Also if you don’t know how to fetch api in ReactJS then you can watch my video on How to fetch API. let’s create small renderData
function outside of our main component to render todo list.
1import React, { useEffect, useState } from "react";
2import "./style.css";
3
4const renderData = (data) => {
5 return (
6
7 <ul>
8 {data.map((todo, index) => {
9 return <li key={index}>{todo.title}</li>;
10 })}
11 </ul>
12
13 );
14};
15
16function PaginationComponent() {
17 const [data, setData] = useState([]);
18
19 useEffect(() => {
20
21 fetch("https://jsonplaceholder.typicode.com/todos")
22 .then((response) => response.json())
23 .then((json) => setData(json));
24
25 }, []);
26
27 return (
28
29 <>
30 <h1>Todo List</h1> <br />
31 {renderData(data)}
32
33 </>
34
35 );
36}
37
38export default PaginationComponent;
39
40
Line no 4 to 12: Here, We have mapped title of to-dos from data state.
Line no 26: Let’s Render renderData(data)
with data state.
Building the logic for pagination
Let’s create two states in PaginationComponent.js
file.
const [currentPage, setcurrentPage] = useState(1);
const [itemsPerPage, setitemsPerPage] = useState(5);
currentPage:
It stores current page number, initially 0.itemsPerPage:
It stores no of items we want to display in single page. Initially it is 5.
const pages = [];
for (let i = 1; i <= Math.ceil(data.length / itemsPerPage); i++) {
pages.push(i);
}
In above code, pages array contains total number of pages like 1, 2, 3..upto (total data / itemsPerPage)
. If you have 20 items and you want to display 5 items per page then you will need 20/5 = 4 pages. Let’s create renderPageNumbers
function which will display page numbers.
1import React, { useEffect, useState } from "react";
2import "./style.css";
3
4const renderData = (data) => {
5 return (
6
7 <ul>
8 {data.map((todo, index) => {
9 return <li key={index}>{todo.title}</li>;
10 })}
11 </ul>
12
13 );
14};
15
16function PaginationComponent() {
17 const [data, setData] = useState([]);
18
19 useEffect(() => {
20
21 fetch("https://jsonplaceholder.typicode.com/todos")
22 .then((response) => response.json())
23 .then((json) => setData(json));
24
25 }, []);
26
27 const handleClick = (event) => {
28
29 setcurrentPage(Number(event.target.id));
30
31 };
32
33 const renderPageNumbers = pages.map((number) => {
34
35 return (
36 <li
37 key={number}
38 id={number}
39 onClick={handleClick}
40 className={currentPage == number ? "active" : null}
41 >
42 {number}
43 </li>
44 );
45
46 });
47
48 return (
49
50 <>
51 <h1>Todo List</h1> <br />
52 {renderData(data)}
53
54 <ul className="pageNumbers">
55 {renderPageNumbers}
56 </ul>
57
58 </>
59
60 );
61}
62
63export default PaginationComponent;
64
65
Line no 27 to 39: Here, we have mapped this pages array which will return an li
tag which display page numbers. This li
tag contains key, id, onClick
method and className
. Here, the className
becomes active
when you are on the same page as currentPage
state.
Line no 23: This handleClick
method runs when we click on any page number and set currentPage
state to selected page number.
Line 47: Here, we have Rendered renderPageNumbers
component by wrapping it with ul
tag and className
as pageNumbers
.
Note: For styling, you can refer pagination css css file.
As you have observed, This page numbers are all over the whole page and now we need to set limit to display this page numbers. To do that we need to define 3 more React states.
const [pageNumberLimit, setpageNumberLimit] = useState(5);
const [maxPageNumberLimit, setmaxPageNumberLimit] = useState(5);
const [minPageNumberLimit, setminPageNumberLimit] = useState(0);
pageNumberLimit:
It is to store how many page numbers you want to display. Here I want to display only 5.maxPageNumberLimit:
It is to store max page bound limit.minPageNumberLimit:
It is to store min page bound limit.
Now let’s modify renderPageNumbers
component by putting if
condition like given below,
const renderPageNumbers = pages.map((number) => {
if (number < maxPageNumberLimit + 1 && number > minPageNumberLimit) {
return (
<li
key={number}
id={number}
onClick={handleClick}
className={currentPage == number ? "active" : null}
>
{number}
</li>
);
} else {
return null;
}
});
This if
condition means that if current number is greater then maxPageNumberLimit+1
and less then minPageNumberLimit
then render it else render nothing. As you run your code, you will see that there are only 5 page numbers displayed. Next we need next
and previous
buttons. Create those buttons around the {renderPageNumbers}
component as in the following code block,
1import React, { useEffect, useState } from "react";
2import "./style.css";
3
4const renderData = (data) => {
5 return (
6
7 <ul>
8 {data.map((todo, index) => {
9 return <li key={index}>{todo.title}</li>;
10 })}
11 </ul>
12
13 );
14};
15
16function PaginationComponent() {
17 const [data, setData] = useState([]);
18
19 useEffect(() => {
20
21 fetch("https://jsonplaceholder.typicode.com/todos")
22 .then((response) => response.json())
23 .then((json) => setData(json));
24
25 }, []);
26
27 const handleClick = (event) => {
28
29 setcurrentPage(Number(event.target.id));
30
31 };
32
33 const renderPageNumbers = pages.map((number) => {
34
35 return (
36 <li
37 key={number}
38 id={number}
39 onClick={handleClick}
40 className={currentPage == number ? "active" : null}
41 >
42 {number}
43 </li>
44 );
45
46 });
47
48 const handleNextbtn = () => {
49 setcurrentPage(currentPage + 1);
50
51 if (currentPage + 1 > maxPageNumberLimit) {
52 setmaxPageNumberLimit(maxPageNumberLimit + pageNumberLimit);
53 setminPageNumberLimit(minPageNumberLimit + pageNumberLimit);
54 }
55
56 };
57
58 const handlePrevbtn = () => {
59
60 setcurrentPage(currentPage - 1);
61
62 if ((currentPage - 1) % pageNumberLimit == 0) {
63 setmaxPageNumberLimit(maxPageNumberLimit - pageNumberLimit);
64 setminPageNumberLimit(minPageNumberLimit - pageNumberLimit);
65 }
66
67 };
68
69 return (
70
71 <>
72 <h1>Todo List</h1> <br />
73 {renderData(data)}
74
75 <ul className="pageNumbers">
76 <li>
77 <button
78 onClick={handlePrevbtn}
79 disabled={currentPage == pages[0] ? true : false}
80 >
81 Prev
82 </button>
83 </li>
84 {renderPageNumbers}
85 <li>
86 <button
87 onClick={handleNextbtn}
88 disabled={currentPage == pages[pages.length - 1] ? true : false}
89 >
90 Next
91 </button>
92 </li>
93 </ul>
94
95 </>
96
97 );
98}
99
100export default PaginationComponent;
101
102
Line no 66-73 and 75-81: There are two buttons prev and next.
Line 41: Here, the handleNextbtn
method is for the next button. In this method whenever user clicks on next
button, it will set the currentPage
state to plus 1 and check the condition whether the current page has crossed maximum page number limit or not. If yes then it will reset this max and min page number limit with new limit.
Line 50: Here is the method for previous button. Only change is in the sign and in the if condition. Suppose you are at page 6 and you want to go back to 5 then this condition will check that 6-1=5%5==0 so it will become true and it will reset max and min page number limits.
Line 69: Here, we have disabled prev
button when user is at 1st page.
Line 78: Here, we have disabled next
button when user is at last page.
Adding Page Indicators
Now our Pagination component is Almost completed one thing left is to add those three dots which indicates that there are more pages then displayed. Let’s create them.
1import React, { useEffect, useState } from "react";
2import "./style.css";
3
4const renderData = (data) => {
5 return (
6 <ul>
7 {data.map((todo, index) => {
8 return <li key={index}>{todo.title}</li>;
9 })}
10 </ul>
11 );
12};
13
14function PaginationComponent() {
15 const [data, setData] = useState([]);
16
17 useEffect(() => {
18 fetch("https://jsonplaceholder.typicode.com/todos")
19 .then((response) => response.json())
20 .then((json) => setData(json));
21 }, []);
22
23 const handleClick = (event) => {
24 setcurrentPage(Number(event.target.id));
25 };
26
27 const renderPageNumbers = pages.map((number) => {
28 return (
29 <li
30 key={number}
31 id={number}
32 onClick={handleClick}
33 className={currentPage == number ? "active" : null}
34 >
35 {number}
36 </li>
37 );
38
39 });
40
41 const handleNextbtn = () => {
42 setcurrentPage(currentPage + 1);
43
44 if (currentPage + 1 > maxPageNumberLimit) {
45 setmaxPageNumberLimit(maxPageNumberLimit + pageNumberLimit);
46 setminPageNumberLimit(minPageNumberLimit + pageNumberLimit);
47 }
48 };
49
50 const handlePrevbtn = () => {
51 setcurrentPage(currentPage - 1);
52
53 if ((currentPage - 1) % pageNumberLimit == 0) {
54 setmaxPageNumberLimit(maxPageNumberLimit - pageNumberLimit);
55 setminPageNumberLimit(minPageNumberLimit - pageNumberLimit);
56 }
57 };
58
59 let pageIncrementBtn = null;
60 if (pages.length > maxPageNumberLimit) {
61 pageIncrementBtn = <li onClick={handleNextbtn}> … </li>;
62 }
63
64 let pageDecrementBtn = null;
65 if (minPageNumberLimit >= 1) {
66 pageDecrementBtn = <li onClick={handlePrevbtn}> … </li>;
67 }
68
69 return (
70 <>
71 <h1>Todo List</h1> <br />
72 {renderData(data)}
73
74 <ul className="pageNumbers">
75 <li>
76 <button
77 onClick={handlePrevbtn}
78 disabled={currentPage == pages[0] ? true : false}
79 >
80 Prev
81 </button>
82 </li>
83 {pageDecrementBtn}
84 {renderPageNumbers}
85 {pageIncrementBtn}
86 <li>
87 <button
88 onClick={handleNextbtn}
89 disabled={currentPage == pages[pages.length - 1] ? true : false}
90 >
91 Next
92 </button>
93 </li>
94 </ul>
95
96 </>
97 );
98}
99
100export default PaginationComponent;
101
Above code block has the full code for this tutorial.
Line no 59 and 64: Here we have created two buttons with hellip; which is unicode for (… ). There are two buttons pageIncrementBtn
will render when page length is > maxPageNumberLimit
. while pageDecrementBtn
will render when minPageNumberLimit
>= 1.
Line no 84 and 86: Here we have rendered both of these (… ) buttons below and after the renderPageNumbers
component.
Now your whole Pagination component is completed. Watch the above video to know about one more pagination component which loads items vertically.