How To set custom pagination in react data grid
Requirements:
In order to done this code,we have to create the following dependencies as listed below
1npm install react-data-grid
Styles:
All the styles are maintained in ./styles.scss and bootstrap 4
1.App {
2 font-family: sans-serif;
3 text-align: center;
4}
5.current-page {
6 font-size: 1.5rem;
7 vertical-align: middle;
8}
9table {
10 width: 100%;
11 overflow-y: hidden;
12}
13tr, td, th {
14 text-align: left;
15 border: 1px solid black;
16 font-size: 18px;
17}
18.user {
19 display: flex;
20 flex-direction: column;
21 justify-content: center;
22 align-items: center;
23}
24.user__body {
25 padding-left: 20px;
26 padding: 20px;
27}
28.current-page {
29 font-size: 1.5rem;
30 vertical-align: middle;
31}
32.pagination-wrapper {
33 display: flex;
34 flex-direction: column;
35 justify-content: center;
36 align-items: center;
37 padding-top: 10 !important;
38}
39.pagination{
40 display: flex;
41}
42.pagination li{
43 list-style: none;
44}
45/* Override some Bootstrap pagination styles */
46ul.pagination {
47 margin-top: 0;
48 margin-bottom: 0;
49 box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
50}
51ul.pagination li.page-item.active a.page-link {
52 color: #445565 !important;
53 background-color: #e3e7eb !important;
54 border-color: #ced4da !important;
55}
56ul.pagination a.page-link {
57 padding: 0.75rem 1rem;
58 min-width: 3.5rem;
59 text-align: center;
60 box-shadow: none !important;
61 border-color: #ced4da !important;
62 color: #6b88a4;
63 font-weight: 900;
64 font-size: 1rem;
65}
66ul.pagination a.page-link:hover {
67 background-color: #f4f4f4;
68}
after installing packages,We have to create a functional component With some unique name.We have to start by creating the data with help of loop .First we have to create the column section ,Here is code of this.
1const columns = [
2 { key: "id", name: "ID" },
3 { key: "title", name: "Title" },
4 { key: "count", name: "Count" }
5];
after creating the column ,we have to create the rows according to loop value.so not need to put json.just run loop and rows will be create automatically
1const [rows] = useState(() => {
2 const rows = [];
3
4 for (let i = 0; i < 1000; i++) {
5 rows.push({
6 id: i,
7 title: Title ${i},
8 count: i * 1000
9 });
10 }
11
12 return rows;
13 });
After doing that now we have to set the NUM_OF_RECORDS,LIMIT,onPageChanged , currentData variables by using some bunch of lines of code .These variables are then sent to pagination component as a props.Now we have to create a ref which is to be passed to DataGrid as a props its help us to scroll the rows on the basis of number entered on the field.
1const [currentPage, setCurrentPage] = useState(1);
2 let NUM_OF_RECORDS = rows.length;
3 let LIMIT = 5;
4 const onPageChanged = useCallback(
5 (event, page) => {
6 event.preventDefault();
7 setCurrentPage(page);
8 },
9 [setCurrentPage]
10 );
11 console.log("jojoj",onPageChanged)
12 const currentData = rows.slice(
13 (currentPage - 1) * LIMIT,
14 (currentPage - 1) * LIMIT + LIMIT
15 );
16 console.log("current dATA", currentPage)
17 const [value, setValue] = useState("10");
18 const gridRef = useRef(null);
19
20 return (
21 <>
22 <div style={{ marginBlockEnd: 5 }}>
23 <span style={{ marginInlineEnd: 5 }}>Row index: </span>
24 <input
25 style={{ inlineSize: 50 }}
26 type="number"
27 value={value}
28 onChange={(event) => setValue(event.target.value)}
29 />
30 <button
31 type="button"
32 onClick={() => gridRef.current.scrollToRow(Number(value))}
33 >
34 Scroll to row
35 </button>
36 </div>
37 <DataGrid
38 ref={gridRef}
39 columns={columns}
40 rows={currentData}
41 direction={direction}
42 className="rdg-light"
43 />
44 <Paginations
45 totalRecords={NUM_OF_RECORDS}
46 pageLimit={LIMIT}
47 pageNeighbours={2}
48 onPageChanged={onPageChanged}
49 currentPage={currentPage}
50 />
51 </>
The whole component look like this:
1import { useState, useRef,useCallback } from "react";
2import DataGrid from "react-data-grid";
3import Paginations from "./paginationComponent";
4import "./styles.css"
5
6const columns = [
7 { key: "id", name: "ID" },
8 { key: "title", name: "Title" },
9 { key: "count", name: "Count" }
10];
11
12export default function ScrollToRow({ direction }) {
13
14 const [rows] = useState(() => {
15 const rows = [];
16
17 for (let i = 0; i < 1000; i++) {
18 rows.push({
19 id: i,
20 title: Title ${i},
21 count: i * 1000
22 });
23 }
24
25 return rows;
26 });
27 const [currentPage, setCurrentPage] = useState(1);
28 let NUM_OF_RECORDS = rows.length;
29 let LIMIT = 5;
30 const onPageChanged = useCallback(
31 (event, page) => {
32 event.preventDefault();
33 setCurrentPage(page);
34 },
35 [setCurrentPage]
36 );
37 console.log("jojoj",onPageChanged)
38 const currentData = rows.slice(
39 (currentPage - 1) * LIMIT,
40 (currentPage - 1) * LIMIT + LIMIT
41 );
42 console.log("current dATA", currentPage)
43 const [value, setValue] = useState("10");
44 const gridRef = useRef(null);
45
46 return (
47 <>
48 <div style={{ marginBlockEnd: 5 }}>
49 <span style={{ marginInlineEnd: 5 }}>Row index: </span>
50 <input
51 style={{ inlineSize: 50 }}
52 type="number"
53 value={value}
54 onChange={(event) => setValue(event.target.value)}
55 />
56 <button
57 type="button"
58 onClick={() => gridRef.current.scrollToRow(Number(value))}
59 >
60 Scroll to row
61 </button>
62 </div>
63 <DataGrid
64 ref={gridRef}
65 columns={columns}
66 rows={currentData}
67 direction={direction}
68 className="rdg-light"
69 />
70 <Paginations
71 totalRecords={NUM_OF_RECORDS}
72 pageLimit={LIMIT}
73 pageNeighbours={2}
74 onPageChanged={onPageChanged}
75 currentPage={currentPage}
76 />
77 </>
78 );
79}
The pagination Component is displayed below:
1import React, { useState, useEffect } from "react";
2const LEFT_PAGE = "LEFT";
3const RIGHT_PAGE = "RIGHT";
4const range = (from, to, step = 1) => {
5 let i = from;
6 const range = [];
7
8 while (i <= to) {
9 range.push(i);
10 i += step;
11 }
12
13 return range;
14};
15
16const Paginations = (props) => {
17 const {
18 totalRecords,
19 pageLimit,
20 pageNeighbours,
21 onPageChanged,
22 currentPage
23 } = props;
24 const [totalPages, setTotalPages] = useState(0);
25 useEffect(() => {
26 setTotalPages(Math.ceil(totalRecords / pageLimit));
27 }, [setTotalPages]);
28
29 const fetchPageNumbers = () => {
30 const totalNumbers = pageNeighbours * 2 + 3;
31 const totalBlocks = totalNumbers + 2;
32
33 if (totalPages > totalBlocks) {
34 const startPage = Math.max(2, currentPage - pageNeighbours);
35 const endPage = Math.min(totalPages - 1, currentPage + pageNeighbours);
36
37 let pages = range(startPage, endPage);
38
39 const hasLeftSpill = startPage > 2;
40 const hasRightSpill = totalPages - endPage > 1;
41 const spillOffset = totalNumbers - (pages.length + 1);
42
43 switch (true) {
44 case hasLeftSpill && !hasRightSpill: {
45 const extraPages = range(startPage - spillOffset, startPage - 1);
46 pages = [LEFT_PAGE, ...extraPages, ...pages];
47 break;
48 }
49 case hasLeftSpill && hasRightSpill:
50 default: {
51 pages = [LEFT_PAGE, ...pages, RIGHT_PAGE];
52 break;
53 }
54 }
55 return [1, ...pages, totalPages];
56 }
57 return range(1, totalPages);
58 };
59
60 const pages = fetchPageNumbers() || [];
61 return (
62 <nav aria-label="Countries Pagination">
63 <ul className="pagination">
64 {pages.map((page, index) => {
65 if (page === LEFT_PAGE)
66 return (
67 <li key={index} className="page-item">
68 <a
69 href="/"
70 className="page-link"
71 aria-label="Previous"
72 onClick={(e) => onPageChanged(e, pageNeighbours * 2 - 1)}
73 >
74 <span aria-hidden="true">«</span>
75 </a>
76 </li>
77 );
78
79 if (page === RIGHT_PAGE)
80 return (
81 <li key={index} className="page-item">
82 <a
83 className="page-link"
84 href="/"
85 aria-label="Next"
86 onClick={(e) => onPageChanged(e, pageNeighbours * 2 + 3)}
87 >
88 <span aria-hidden="true">»</span>
89 </a>
90 </li>
91 );
92
93 return (
94 <li
95 key={index}
96 className={page-item${currentPage === page ? " active" : ""}}
97 >
98 <a
99 className="page-link"
100 href="/"
101 onClick={(e) => onPageChanged(e, page)}
102 >
103 {page}
104 </a>
105 </li>
106 );
107 })}
108 </ul>
109 </nav>
110 );
111};
112
113export default Paginations;
Here is the link of live example which we done so far:
Click here
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: