Reputation: 153
I am using React + Material Table.
What to achieve
I want to have the option to set pageSize to 'All' to match to total count of rows in material-table.
What I have done
I use useState
to create rowsPerPage , and set rowsPerPage in the handleChangeRowsPerPage function. I use component overriding to customize the Pagination and pass rowsPerPage and handler to its props. I also pass rowsPerPage to MaterialTable's pageSize option.
Problem I encounter
The page does not re-size, and the state.pageSize does not update. Even though the props.options.pageSize and Pagination successfully update with onChangeRowsPerPage.
Link to sandbox
import React, { useState } from "react";
import MaterialTable from "material-table";
import { TablePagination } from "@material-ui/core";
export default function ComponentOverriding() {
const [rowsPerPage, setRowsPerPage] = useState(5);
//updates pagination, but no re-size
const handleChangeRowsPerPage = event => {
//enable to set rows per page to match total count
event.target.value === "All"
? setRowsPerPage(data.length)
: setRowsPerPage(event.target.value);
};
const data = [
{ name: "Mehmet", surname: "Baran", birthYear: 1987 },
{ name: "Zerya Betül", surname: "Baran", birthYear: 2017 }
];
return (
<MaterialTable
title="Component Override Demo"
columns={[
{ title: "Name", field: "name" },
{ title: "Surname", field: "surname" },
{ title: "Birth Year", field: "birthYear" }
]}
data={data}
//options.pageSize updates, but no re-size
options={{ pageSize: rowsPerPage }}
// onChangeRowsPerPage={handleChangeRowsPerPage} //TypeError Cannot read property 'value' of undefined
components={{
Pagination: props => (
<TablePagination
{...props}
rowsPerPageOptions={[5, 10, 20, "All"]}
rowsPerPage={rowsPerPage}
//updates pagination, but no re-size
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
)
}}
/>
);
}
Upvotes: 11
Views: 11266
Reputation: 343
Just to add a little to Ashish's answer, you should also make sure that data.length
is no equal to zero or else in the rows drop down menu you will get [object Object] rows
when you select All
.
<MaterialTable
options={{
pageSize: rowsPerPage,
pageSizeOptions: [5, 10, 20, { value: data.length > 0 ? data.length : 1, label: 'All' }],
}}
/>
Upvotes: 1
Reputation: 91
I got a solution, no need to customize pagination just replace
<MaterialTable
options={{
pageSize: rowsPerPage,
pageSizeOptions: [5, 10, 20],
}}
/>
with
<MaterialTable
options={{
pageSize: rowsPerPage,
pageSizeOptions: [5, 10, 20, { value: data.length, label: 'All' }],
}}
/>
Upvotes: 9