In this tutorial, I will show you how to implement pagination on react table using Material UI.
- Define the page and rowsPerPage States
- Setup the handleChangePage Function
- Setup the handleChangeRowsPerPage Function
- Slice the Product List
- Display the TablePagination Component
- Fix the Pagination Buttons Alignment
Prerequisites:
You’ve fetched some data from an api endpoint and displayed it on a table and now you want to add a neat pagination at the bottom of the table. The steps are as follows:
1. Define the page and rowsPerPage States
The page is the variable that holds the current page while the rowsPerPage holds the value of the number of records in a single page.
const [page, setPage] = useState(0); // Current page index const [rowsPerPage, setRowsPerPage] = useState(5); // Number of rows per page
2. Setup the handleChangePage Function
This is the function that runs when a user changes page (either moves to next or previous page)
// Handle page change const handleChangePage = (event, newPage) => { setPage(newPage); };
3. Setup the handleChangeRowsPerPage Function
This is the function that gets called when a user selects the rows per page value from the dropdown.
// Handle change in rows per page const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); // Reset the table to the first page whenever rows per page changes };
4. Slice the Products List
Now we must slice the products list based on the current page and the rows per page. And this slice is what would be displayed. Therefore, before you map, you must add the slice like so:
products.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
5. Display the TablePagination Component
This is part of the Material ui components and shown below:
<TablePagination component="div" count={products.length} page={page} onPageChange={handleChangePage} rowsPerPage={rowsPerPage} onRowsPerPageChange={handleChangeRowsPerPage} rowsPerPageOptions={[5, 10, 25]} // Options for rows per page />
6. Fix the Pagination Buttons Alignment (Material UI >5)
If you are using Material UI >5, then the alignment of the pagination buttons would not display as expected. To fix that, you have to do two things:
- install bootstrap
npm install bootstrap@3
- modify the sx prop of the TablePagination component using the code below
sx={{ ".MuiTablePagination-displayedRows, .MuiTablePagination-selectLabel": { "margin-top": "1em", "margin-bottom": "1em" } }}
At this point, you are all set, you can fire up the application using ‘npm run start’ and enjoy!!