In this article, we will create a custom component in React that allows users to set the number of rows displayed per page in a data table. We will utilize the PrimeReact library for our data table and pagination functionality.
Prerequisites
Before you start, ensure you have the following:
A React environment set up (e.g., using Create React App).
Installed PrimeReact and Bootstrap:
npm install primereact primeicons bootstrap
Import PrimeReact CSS in your index.js or App.js:
import 'primereact/resources/themes/saga-blue/theme.css'; // Choose your theme
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import 'bootstrap/dist/css/bootstrap.min.css';
Code Implementation
Now, let’s create the CustomRowsPerPageTop component.
import React, { useState } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'react-bootstrap';
const CustomRowsPerPageTop = () => {
const [products, setProducts] = useState([
{ id: 1, name: 'Apple', price: 1.5 },
{ id: 2, name: 'Banana', price: 1.2 },
{ id: 3, name: 'Orange', price: 1.8 },
{ id: 4, name: 'Grapes', price: 2.0 },
{ id: 5, name: 'Mango', price: 1.6 },
{ id: 6, name: 'Pineapple', price: 2.5 },
{ id: 7, name: 'Strawberry', price: 3.0 },
{ id: 8, name: 'Blueberry', price: 2.8 },
{ id: 9, name: 'Kiwi', price: 2.2 },
{ id: 10, name: 'Peach', price: 1.9 }
]);
const [rowsPerPage, setRowsPerPage] = useState(5);
const rowsPerPageOptions = [5, 10, 15, 20];
const onRowsPerPageChange = (event) => {
setRowsPerPage(event.target.value);
};
const paginatorLeft = ;
const paginatorRight = ;
return (
Rows per page:
{rowsPerPageOptions.map((option) => (
{option}
))}
);
};
export default CustomRowsPerPageTop;
Explanation of the Code
State Management: We use the useState hook to manage the list of products and the number of rows displayed per page.You can also see datatable of tiktok video saver
DataTable Component: The DataTable component from PrimeReact is used to render the table. It accepts several props including value, paginator, rows, and rowsPerPageOptions.
Rows Per Page Selector: A dropdown is provided to allow users to select how many rows they want to display. This updates the rowsPerPage state when changed.
Paginator: We customize the paginator by defining what buttons should appear on either side of it (e.g., refresh and download buttons).
Columns: Each column is defined using the Column component, specifying the field to display and the header title.
Conclusion
This example demonstrates how to create a customizable data table with pagination in React using PrimeReact. You can easily expand upon this by adding more features such as sorting, filtering, or editing capabilities based on your application needs.