React Table - Sever Side Pagination, Search, Sort/Order
Metaphore Name
React Table - Sever Side Pagination, Search, Sort/Order
Share your metaphore story!
TLDR
This is a complete guide how I manage datatable in React JS project using react-table
and prisma
ORM. Let's start!
Client Side
1// Component Filename: TablePagination.js 2 3import { 4 ArrowLongDownIcon, 5 ArrowLongUpIcon, 6 FunnelIcon, 7} from '@heroicons/react/24/outline'; 8import { ClockIcon } from '@heroicons/react/24/solid'; 9import React from 'react'; 10import { 11 useAsyncDebounce, 12 useGlobalFilter, 13 usePagination, 14 useSortBy, 15 useTable, 16} from 'react-table'; 17 18function TablePagination({ 19 columns, 20 data, 21 fetchData, 22 loading, 23 pageCount: controlledPageCount, 24 totalRow, 25 actions: Actions, 26}) { 27 const { 28 getTableProps, 29 getTableBodyProps, 30 headerGroups, 31 prepareRow, 32 page, 33 canPreviousPage, 34 canNextPage, 35 pageOptions, 36 pageCount, 37 gotoPage, 38 nextPage, 39 previousPage, 40 setPageSize, 41 state: { pageIndex, pageSize, globalFilter, sortBy }, 42 preGlobalFilteredRows, 43 setGlobalFilter, 44 } = useTable( 45 { 46 columns, 47 data, 48 manualPagination: true, 49 manualGlobalFilter: true, 50 manualSortBy: true, 51 initialState: { 52 pageIndex: 0, 53 pageSize: 10, 54 }, // Pass our hoisted table state 55 pageCount: controlledPageCount, 56 autoResetSortBy: false, 57 autoResetExpanded: false, 58 autoResetPage: false, 59 }, 60 useGlobalFilter, 61 useSortBy, 62 usePagination 63 ); 64 65 const GlobalFilter = ({ 66 preGlobalFilteredRows, 67 globalFilter, 68 setGlobalFilter, 69 }) => { 70 const count = preGlobalFilteredRows; 71 const [value, setValue] = React.useState(globalFilter); 72 const onChange = useAsyncDebounce((value) => { 73 setGlobalFilter(value || undefined); 74 }, 700); 75 76 return ( 77 <div 78 className={ 79 Actions !== undefined 80 ? 'flex flex-row justify-between' 81 : 'flex flex-col' 82 } 83 > 84 {Actions !== undefined ? <Actions /> : null} 85 <input 86 value={value || ''} 87 onChange={(e) => { 88 setValue(e.target.value); 89 onChange(e.target.value); 90 }} 91 placeholder={`${count} records...`} 92 type="search" 93 className={`input input-bordered input-sm w-full max-w-xs focus:outline-0 mb-2 ${ 94 Actions !== undefined ? '' : 'self-end' 95 }`} 96 /> 97 </div> 98 ); 99 }; 100 101 React.useEffect(() => { 102 let search = globalFilter === undefined ? '' : globalFilter; 103 fetchData(pageSize, pageIndex, search, sortBy); 104 }, [fetchData, pageIndex, pageSize, globalFilter, sortBy]); 105 106 return ( 107 <> 108 <GlobalFilter 109 preGlobalFilteredRows={totalRow} 110 globalFilter={globalFilter} 111 setGlobalFilter={setGlobalFilter} 112 /> 113 <div className="overflow-x-auto relative"> 114 <table 115 {...getTableProps()} 116 className="table table-compact table-zebra w-full" 117 > 118 <thead> 119 {headerGroups.map((headerGroup) => ( 120 <tr {...headerGroup.getHeaderGroupProps()}> 121 {headerGroup.headers.map((column) => ( 122 <th {...column.getHeaderProps(column.getSortByToggleProps())}> 123 <span> 124 {column.isSorted ? ( 125 column.isSortedDesc ? ( 126 <ArrowLongDownIcon className="h-4 w-4 inline mr-1" /> 127 ) : ( 128 <ArrowLongUpIcon className="h-4 w-4 inline mr-1" /> 129 ) 130 ) : ( 131 <FunnelIcon className="h-4 w-4 inline mr-1" /> 132 )} 133 </span> 134 {column.render('Header')} 135 </th> 136 ))} 137 </tr> 138 ))} 139 </thead> 140 <tbody {...getTableBodyProps()}> 141 {page.length > 0 ? ( 142 page.map((row, i) => { 143 prepareRow(row); 144 return ( 145 <tr {...row.getRowProps()} className="hover"> 146 {row.cells.map((cell) => { 147 return ( 148 <td {...cell.getCellProps()}>{cell.render('Cell')}</td> 149 ); 150 })} 151 </tr> 152 ); 153 }) 154 ) : ( 155 <tr className="hover"> 156 <td colSpan={10000} className="text-center"> 157 Data not found! 158 </td> 159 </tr> 160 )} 161 </tbody> 162 </table> 163 {loading ? ( 164 <div className="absolute top-0 bottom-0 left-0 right-0 bg-black bg-opacity-5 rounded-md z-20 flex items-center justify-center"> 165 <div className="absolute p-3 bg-white w-36 shadow-md rounded-md text-center"> 166 <div className="flex animate-pulse"> 167 <ClockIcon className="w-6 h-6 mr-1" /> <span>Loading...</span> 168 </div> 169 </div> 170 </div> 171 ) : null} 172 </div> 173 <div className="flex flex-row justify-between"> 174 <div className="mt-2"> 175 <span> 176 Halaman{' '} 177 <strong> 178 {pageIndex + 1} dari {pageOptions.length} 179 </strong>{' '} 180 Total <strong>{preGlobalFilteredRows.length}</strong>{' '} 181 </span> 182 <span> 183 | Lompat ke halaman:{' '} 184 <input 185 type="number" 186 defaultValue={pageIndex + 1} 187 onChange={(e) => { 188 const page = e.target.value ? Number(e.target.value) - 1 : 0; 189 gotoPage(page); 190 }} 191 className="input input-bordered input-sm w-20 max-w-xs focus:outline-0" 192 /> 193 </span> <select 194 value={pageSize} 195 onChange={(e) => { 196 setPageSize(Number(e.target.value)); 197 }} 198 className="select select-bordered select-sm w-30 max-w-xs focus:outline-0" 199 > 200 {[10, 20, 30, 40, 50].map((pageSize) => ( 201 <option key={pageSize} value={pageSize}> 202 Tampilkan {pageSize} baris 203 </option> 204 ))} 205 </select> 206 </div> 207 <div className="mt-2"> 208 <button 209 className="btn btn-xs" 210 onClick={() => gotoPage(0)} 211 disabled={!canPreviousPage} 212 > 213 {'<<'} 214 </button>{' '} 215 <button 216 className="btn btn-xs" 217 onClick={() => previousPage()} 218 disabled={!canPreviousPage} 219 > 220 {'<'} 221 </button>{' '} 222 <button 223 className="btn btn-xs" 224 onClick={() => nextPage()} 225 disabled={!canNextPage} 226 > 227 {'>'} 228 </button>{' '} 229 <button 230 className="btn btn-xs" 231 onClick={() => gotoPage(pageCount - 1)} 232 disabled={!canNextPage} 233 > 234 {'>>'} 235 </button>{' '} 236 </div> 237 </div> 238 </> 239 ); 240} 241 242export default TablePagination;
Dependencies
The component above generates a table with global filtering, pagination, sorting, and loading features. It uses the following dependencies: @heroicons/react
for icons, react
for the base library, and react-table
for generating the table.
Table Instance
TablePagination
is a function that receives props that are used to display the table. The props are columns
for the table columns, data
for the data to be displayed, fetchData
for fetching data when pagination is changed, loading
to display the loading icon, pageCount
for the number of pages, totalRow
for the total row count, and actions
for extra action buttons on the filter row.
The function creates a table instance using useTable
from react-table
and initializes the state of the table to the first page and ten rows per page. It also sets manualPagination
, manualGlobalFilter
, and manualSortBy
to true
so that the component has control over those features.
Global Filtering
The GlobalFilter
component displays the input search box used for filtering the table data. It also receives the pre-filtered row count and uses useAsyncDebounce
to delay the search filter until the user stops typing. This helps reduce unnecessary calls to the server when searching.
Table Body
The table body and header are then created using the getTableProps
and getTableBodyProps
methods from the react-table library. The headerGroups
and page are used to map over the header columns and table data, respectively, using the map function. The prepareRow
method is called on each row to enable the use of the getRowProps
and getCellProps
methods to style the row and cell.
Sorting
The sorting feature is enabled by adding the getHeaderProps
method to the column header and using the column.getSortByToggleProps()
method. This method updates the sortBy
object in the table state and adds the appropriate class and icon to the sorted column.
Pagination
The pagination feature is enabled using usePagination
and the pageCount
, canPreviousPage
, canNextPage
, pageOptions
, gotoPage
, nextPage
, previousPage
, and setPageSize
methods. These methods are used to generate the pagination controls and update the table state when the user interacts with them.
Loading
Finally, the loading feature is enabled by checking if loading
is true and displaying a loading icon in the table while data is being fetched from the server.
Helpers
When we use API for pagination we also need a helper to serialized endpoint url before sending to server.
1// Filename: uriSerialized.js 2const Util = { 3 isArray: function (val) { 4 return Object.prototype.toString.call(val) === '[object Array]'; 5 }, 6 isNil: function (val) { 7 return val === null || Util.typeOf(val); 8 }, 9 typeOf: function (val, type) { 10 return (type || 'undefined') === typeof val; 11 }, 12 funEach: function (obj, fun) { 13 if (Util.isNil(obj)) return; // empty value 14 15 if (!Util.typeOf(obj, 'object')) obj = [obj]; // Convert to array 16 17 if (Util.isArray(obj)) { 18 // Iterate over array 19 for (var i = 0, l = obj.length; i < l; i++) 20 fun.call(null, obj[i], i, obj); 21 } else { 22 // Iterate over object 23 for (var key in obj) 24 Object.prototype.hasOwnProperty.call(obj, key) && 25 fun.call(null, obj[key], key, obj); 26 } 27 }, 28}; 29 30export const uriSerialized = (params) => { 31 let pair = []; 32 33 const encodeValue = (v) => { 34 if (Util.typeOf(v, 'object')) v = JSON.stringify(v); 35 36 return encodeURIComponent(v); 37 }; 38 39 Util.funEach(params, (val, key) => { 40 let isNil = Util.isNil(val); 41 42 if (!isNil && Util.isArray(val)) key = `${key}[]`; 43 else val = [val]; 44 45 Util.funEach(val, (v) => { 46 pair.push(`${key}=${isNil ? '' : encodeValue(v)}`); 47 }); 48 }); 49 50 return pair.join('&'); 51};
This code defines an object named Util
, which contains several utility functions:
isArray
checks whether a given value is an array or not. It does this by using theObject.prototype.toString.call
method, which returns a string representing the object's type. If the string matches the expected value "[object Array]
", then the value is considered an array.isNil
checks whether a given value is null or undefined. It does this by using thetypeOf
method to check if the type of the value is "undefined".typeOf
checks whether the given value is of a certain type. It does this by comparing the type of the value to the type provided as an argument. If the types match, it returns true.funEach
is a utility function that can iterate over an array or an object and execute a given function for each element. If the given value is null or undefined, the function simply returns. If the value is not an object, it converts it to an array. If the value is an array, it iterates over each element and calls the given function with the element, index, and array as arguments. If the value is an object, it iterates over each key-value pair and calls the given function with the value, key, and object as arguments.
The code then exports a function named uriSerialized
. This function takes an object params
as input and returns a string representing the object as a URI-encoded string.
The function uses Util.funEach
to iterate over the object and create an array of key-value pairs, where each value is URI-encoded. If the value is an array, the key is modified by appending "[]" to the end. The key-value pairs are then concatenated into a string with "&" as the separator, and returned.
Services
For example when we need to create datatable for roles designation on a system.
1import axios from 'axios'; 2import { uriSerialized } from '../Utils/uriSerialized'; 3 4export const getRoleDatatable = async (queryOptions = null) => { 5 try { 6 const query = queryOptions ? '?' + uriSerialized(queryOptions) : ''; 7 const request = await axios({ 8 method: 'GET', 9 url: `/roles/datatable${query}`, 10 }); 11 const response = request.data; 12 return response; 13 } catch (error) { 14 console.log(`getRoleDatatable error: ${error}`); 15 return false; 16 } 17};
This function makes a GET request to an API endpoint for a role datatable using the Axios HTTP client library.
The function accepts an optional parameter queryOptions
which can be used to pass in query parameters to the API endpoint. If queryOptions
is not null, it will be converted to a serialized URI string using the uriSerialized
function imported from "../Utils/uriSerialized". The serialized URI string is then appended to the API endpoint URL.
The function then sends the HTTP request to the API endpoint using axios, and awaits for the response data. If the request is successful, the response data is returned. If the request fails, the error message is logged to the console and the function returns false
.
The Role Datatable
Woooooooooooooooooooooooooo.... implementing in RoleDatatable
component
1import React, { useState, useCallback, useMemo } from 'react'; 2import { getRoleDatatable } from '../../../services/roles'; 3import TablePagination from '../../TablePagination'; 4import { PencilSquareIcon, TrashIcon } from '@heroicons/react/24/solid'; 5 6function RoleDatatable() { 7 const [data, setData] = useState([]); 8 const [loading, setLoading] = useState(false); 9 const [pageCount, setPageCount] = useState(0); 10 const [totalRow, setTotalRow] = useState(0); 11 12 const fetchData = useCallback(async (pageSize, pageIndex, search, order) => { 13 setLoading(true); 14 const queryOptions = { 15 page: pageIndex, 16 limit: pageSize, 17 search: search, 18 order: order, 19 }; 20 const items = await getRoleDatatable(queryOptions); 21 22 setData(items.data); 23 setPageCount(items.pagination.totalPage); 24 setTotalRow(items.pagination.totalRow); 25 setLoading(false); 26 }, []); 27 28 const columns = useMemo( 29 () => [ 30 { 31 Header: '#', 32 accessor: 'roleId', 33 Cell: ({ row }) => `R#${row.original.roleId}`, 34 disableSortBy: true, 35 }, 36 { 37 Header: 'Role Name', 38 accessor: 'roleName', 39 }, 40 { 41 Header: 'Role Key', 42 accessor: 'roleKey', 43 Cell: ({ row }) => row.original.roleKey, 44 }, 45 { 46 Header: 'Action', 47 accessor: ({ row }) => { 48 return ( 49 <div className="flex gap-2"> 50 <button className="btn btn-xs btn-info"> 51 <PencilSquareIcon className="w-4 h-4" /> 52 </button> 53 <button className="btn btn-xs btn-error"> 54 <TrashIcon className="w-4 h-4" /> 55 </button> 56 </div> 57 ); 58 }, 59 }, 60 ], 61 [] 62 ); 63 64 return ( 65 <section> 66 <TablePagination 67 columns={columns} 68 data={data} 69 fetchData={fetchData} 70 loading={loading} 71 pageCount={pageCount} 72 totalRow={totalRow} 73 /> 74 </section> 75 ); 76} 77 78export default RoleDatatable;
This is a functional React component that fetches data from the server, displays it in a paginated table, and provides the user with some action buttons for each item.
The component uses the useState
hook to maintain its internal state, which includes data
, loading
, pageCount
, and totalRow
. The fetchData
function is a useCallback
hook, which makes an API call to the server with some query parameters to fetch the data, updates the state variables, and sets the loading flag.
The component also uses the useMemo
hook to memoize the columns
object that contains an array of objects, which define the headers of the table columns, their accessor functions, and a Cell
function that returns the corresponding value for each row. The last column of the table has two buttons, PencilSquareIcon
and TrashIcon
, to allow the user to edit or delete an item.
The TablePagination
component is a custom component that receives columns
, data
, fetchData
, loading
, pageCount
, and totalRow
as its props. This component is responsible for rendering the table, paginating it, and displaying the loading
spinner while the data is being fetched. When the user clicks on the pagination links, fetchData
is called with the new page index and page size, which triggers a new API call to the server with the updated query parameters.
Finally, the component is exported as the default export, which can be imported and used in other parts of the application.
That's the client side things!!! Terrace done!
Server Side
Now move on the server side, we will use prisma
as ORM in Express API.
Dependencies:
- lodash
- prisma
- a cup of coffee
Role Datatable Model
1// Filename: Roles.js 2const { PrismaClient } = require('@prisma/client'); 3const db = new PrismaClient(); 4const _ = require('lodash'); 5 6exports.roleDatatable = async ( 7 page = 0, 8 limit = 10, 9 search = '', 10 order = [] 11) => { 12 try { 13 var paginate = limit * page - 1; 14 var offset = paginate < 0 ? 0 : paginate; 15 const sort = _.isEmpty(order) ? [] : JSON.parse(_.first(order)); 16 const orderKey = _.isEmpty(sort) ? 'roleName' : sort.id; 17 const orderDirection = _.isEmpty(sort) 18 ? 'desc' 19 : sort.desc 20 ? 'desc' 21 : 'asc'; 22 23 const roles = await db.roles.findMany({ 24 where: { 25 OR: [ 26 { 27 roleName: { 28 contains: search, 29 }, 30 }, 31 ], 32 isDeleted: false, 33 }, 34 skip: Number(offset), 35 take: Number(limit), 36 orderBy: { 37 [orderKey]: orderDirection, 38 }, 39 }); 40 41 const countTotal = await db.roles.count({ 42 where: { 43 OR: [ 44 { 45 roleName: { 46 contains: search, 47 }, 48 }, 49 ], 50 isDeleted: false, 51 }, 52 }); 53 54 return { 55 data: roles, 56 totalRow: countTotal, 57 totalPage: Math.ceil(countTotal / limit), 58 }; 59 } catch (error) { 60 console.log(`Error on roleDatatable: ${error}`); 61 return false; 62 } 63};
function called roleDatatable
that queries a database to retrieve a paginated list of roles based on the given search criteria, sorting and pagination.
The function takes four optional parameters: page
, limit
, search
and order
. page
and limit
are used to determine the page size and the number of records to return, while search is used to filter the records based on a text string. order is an array that specifies the order
in which the records should be sorted.
Inside the function, the paginate
and offset
variables are used to calculate the number of records to skip and take. The sort
, orderKey
, and orderDirection
variables are used to specify the order by which the records should be sorted.
The function then queries the database using db.roles.findMany()
, passing in the search criteria, pagination and sorting options. It also queries the total count of roles that match the search criteria, which is used to calculate the total number of pages.
The function returns an object that contains the paginated roles, the total number of rows, and the total number of pages. If an error occurs, it logs the error and returns false.
Helpers
I need to format server response that sent to client using formatResponse
helper
1// Filename: helpers/formatResponse.js 2module.exports = ( 3 type, 4 message = 'No desription', 5 data = [], 6 pagination = null 7) => { 8 const ALLOWED_TYPES = [ 9 'VALID', 10 'INVALID', 11 'FOUND', 12 'NOT_FOUND', 13 'INTERNAL_ERROR', 14 'CREATED', 15 'NOT_MODIFIED', 16 'NOT_AUTHORIZED', 17 'FORBIDDEN', 18 ]; 19 if (!ALLOWED_TYPES.includes(type)) { 20 throw `${type} is not allowed. Available type is ${ALLOWED_TYPES.join( 21 ', ' 22 )}`; 23 } 24 return pagination === null 25 ? { type, message, data } 26 : { type, message, data, pagination }; 27};
The function takes in four parameters: type
(a string), message
(a string with a default value of "No description"), data
(an array with a default value of an empty array), and pagination
(an optional object).
The function returns an object with the properties type
, message
, and data
, and, if pagination
is not null
, includes the pagination
object as well.
Before returning the object, the function checks if the type
parameter is one of the allowed types by comparing it to an array of allowed types. If the type
is not allowed, an error is thrown indicating which types are allowed.
Router
Let's create API route for Role Datatable
1// Filename: routes/roles.js 2const express = require('express'); 3const formatResponse = require('../../helpers/formatResponse'); 4const { roleDatatable } = require('../../models/Roles'); 5 6const router = express.Router(); 7 8router.get('/datatable', async (req, res) => { 9 const { page, limit, search, order } = req.query; 10 const roles = await roleDatatable(page, limit, search, order); 11 if (roles) { 12 res.status(200).json( 13 formatResponse('FOUND', 'Roles datatable', roles.data, { 14 totalRow: roles.totalRow, 15 totalPage: roles.totalPage, 16 }) 17 ); 18 } else { 19 res.status(404).json(formatResponse('NOT_FOUND', 'No data roles')); 20 } 21}); 22 23module.exports = router;
his code sets up a router for an endpoint that returns a datatable of roles. The endpoint listens for GET requests to the '/datatable' path. When a request is received, it extracts the query parameters (page, limit, search, and order) from the request. It then calls the roleDatatable
function from the Roles model with the query parameters. If roleDatatable
returns data, the endpoint sends a response with a 200 status code and a JSON object containing the datatable data and pagination information. If roleDatatable
returns no data, the endpoint sends a response with a 404 status code and a JSON object containing an error message.
The formatResponse
function is used to format the response into a standard structure. It takes four parameters: type (a string that indicates the type of response), message (a string that provides additional details about the response), data (the data to be included in the response), and pagination (an optional object that contains pagination information). It returns an object that includes the four parameters.
Fiuh!!!! that's it... no puncline...
A demo/repos link
No response