Set pagination on MaterialTable ui https://material-table.com/#/docs/features/localization? - reactjs

That is my code. I would like to set pagination to 50, 100, 250 rows per page (for example). How can I achieve that?
<MaterialTable
localization={{
pagination: {
labelDisplayedRows: '4-6 of 10',
labelRowsPerPage:'{5, 10, 25,100}'
},
}}
title="Crawler Results"
columns={[
{ title: "URL", field: "url" },
{ title: "Status", field: "status" }
]}
data={state.data}
actions={[
{
icon: 'add',
tooltip: 'Add User',
isFreeAction: true,
onClick: () => {
//show crawler table and hide formular
document.getElementById('formCrawler').style.display = "block";
document.getElementById('formSpan').style.display = "block";
document.getElementById('crawlerTableID').style.display = "none";
}
}]}
/>

As mentioned in the docs, you can override the pageSizeOptions in options with an array of page sizes.
<MaterialTable
localization={{
pagination: {
labelDisplayedRows: '4-6 of 10',
labelRowsPerPage:'{5, 10, 25,100}'
},
}}
title="Crawler Results"
columns={[
{ title: "URL", field: "url" },
{ title: "Status", field: "status" }
]}
options={{
pageSizeOptions : [50, 100, 200]
}}
data={state.data}
actions={[
{
icon: 'add',
tooltip: 'Add User',
isFreeAction: true,
onClick: () => {
//show crawler table and hide formular
document.getElementById('formCrawler').style.display = "block";
document.getElementById('formSpan').style.display = "block";
document.getElementById('crawlerTableID').style.display = "none";
}
}]}
/>

Adding labelRowsPerPage didn't do anything for me. I added the following property to the MaterialTable:
options={{
pageSizeOptions: [50, 100, 250]
}}
https://material-table.com/#/docs/all-props

Related

Using MUI DataGrid, how to update a cell state onChange?

What I need: I'm using MUI DataGrid > 5. I need that the data that is filled in a cell change automatically the state (onChange). At this moment, I have an useEffect that is listening to these changes to “enable/disable” the “Save” and “Cancel” buttons.
What I tried: Using onCellEditCommit property, it saves the cell content only when I click outside the DataGrid component (or when I press tab or enter). I would like to save the content on cell change.
...
import {
DataGrid,
GridColDef,
GridPreProcessEditCellProps,
GridRowId,
} from "#mui/x-data-grid";
...
const [devices, setDevices] = useState<Device[]>(formValues.devices);
const columns: GridColDef[] = [
{
field: "id",
headerName: "ID",
flex: 10,
},
{
field: "uniqueIdentification",
headerName: "Unique ID",
editable: true,
flex: 30,
},
{
field: "description",
headerName: "Description",
editable: true,
flex: 50,
},
{
field: "isActive",
headerName: "Active",
type: "boolean",
editable: true,
flex: 10,
},
{
field: "actions",
type: "actions",
headerName: "Actions",
width: 100,
cellClassName: "actions",
renderCell: (params) => (
<Box id={`${params.id}`} component="div">
<IconButton
title="Remove"
onClick={() => deleteRow(params.id)}
size="small"
>
<DeleteIcon />
</IconButton>
</Box>
),
},
];
function saveDeviceCell(params) {
const oldDevices = [...devices];
const rowDeviceIndex = oldDevices.findIndex((dev) => dev.id === params.id);
oldDevices[rowDeviceIndex] = {
...oldDevices[rowDeviceIndex],
[params.field]: params.value,
};
setDevices(oldDevices);
}
...
return (
<DataGrid
rows={devices}
columns={columns}
hideFooterPagination
hideFooter
disableSelectionOnClick
autoHeight
onCellEditCommit={saveDeviceCell}
editMode="cell"
/>
...
);

React Ag-grid displaying

When I add simple table on my page:
...
const [columnDefs] = useState([
{ headerName: "id", field: "id" },
{ headerName: "name", field: "name" },
{ headerName: "type", field: "type" },
]);
const defaultColDef = useMemo(() => {
return {
flex: 1,
minWidth: 140,
resizable: true,
};
}, []);
return (
<>
<div className="ag-theme-alpine" style={{ height: 400, width: 500 }}>
<AgGridReact
rowData={foundTemplates}
columnDefs={columnDefs}
getRowId={getRowId}
defaultColDef={defaultColDef}></AgGridReact>
pagination={false}
</div>
</>
);
foundTemplates has the following structure:
{ id: 1, name: "testName1", type: "TestRFQ", description: "description1", ownerCurrentUser: true, lastUsed: true },
{ id: 2, name: "testName2", type: "TestRFI", description: "description2", ownerCurrentUser: false, lastUsed: true },
{ id: 3, name: "testName3", type: "TestAuction", description: "description3", ownerCurrentUser: true, lastUsed: false },
{ id: 4, name: "testName4", type: "TestAuction", description: "description4", ownerCurrentUser: false, lastUsed: false },
I have a problem with displaying data in the right way:
all data is displaying in one column (despite I have some kind of column definitions with 3 fields at least). Also I've tried to remove a pagination block (pagination={false}), but it is still displaying.
How it looks now
In general I'm planning to use custom cell renderer for info displaying, but now I can't even display a simple data.
The root cause: I didn't import ag-grid css.

Prevent user from entering negative number validation material-table

How can I prevent the user from adding a negative number to my table? I thought that having the type: numeric would do the trick but I still can enter a negative number into it.
Could I create a function and added to my promise?
<MaterialTable
aria-label="List of pseudopotentials"
icons={tableIcons}
title="Pseudopotentials"
columns={[
{title: 'Element', field: 'kind', editable: 'never'},
{title: 'Atomic Mass (AMU)', field: 'atomic_mass', type: 'numeric'}, <----- TYPE NUMERIC HERE
{title: 'Filename', field: 'filename', editable: 'never'},
]}
data={createTable(selectedPseudos, customAtomicMasses)}
options={{
paging: false,
rowStyle: (x: {tableData: {id: number}}) => {
if (x.tableData.id % 2) {
return {backgroundColor: '#ddd'}
}
},
maxBodyHeight: '25em',
headerStyle: {
backgroundColor: '#ddd',
padding: '0.25em 1em',
fontWeight: 'bolder',
},
}}
editable={{
/** NEED TO PREVENT NEGATIVE NUMBER*/
onRowUpdate: (newData) =>
new Promise((resolve) => {
const newMasses = {...customAtomicMasses}
newMasses[newData.kind] = newData.atomic_mass
setCustomAtomicMasses(newMasses)
resolve(0)
}),
}}
actions={[
{
icon: () => {
return <Search aria-label="search-pseudopotentials" />
},
tooltip: 'Search pseudopotentials',
onClick: (_event, rowData) => {
setModalKind(rowData.kind)
setShowModal(true)
},
},
]}
></MaterialTable>

Execute function when I apply filter, material-table

I am working with Material_table, what I am looking for is that when my user applies a filter to send a method
I want to call this method
const subscribeRemoteRequestsArticle = (id) => {
subscriptionRemoteRequests = API.graphql(
.....
.....
}
Table
<MaterialTable
icons={tableIcons}
columns={[
{
field: "clacte",
title: props.translate("Key"),
/* customFilterAndSearch: (term, rowData) => subscribeRemoteRequestsArticle <-- here perform the test */
},
{
field: "nomcte",
title: props.translate("Customers"),
},
{
field: "nomemp",
title: props.translate("Company Key"),
},
{
field: "nomregion",
title: props.translate("Name region"),
},
{
field: "nomgirocom",
title: props.translate("Commercial Business"),
/* lookup: "NomGiroCom", */
},
]}
data={customerList}
title={props.translate("List of customers")} //
options={{
selection: true,
filtering: true,
search: false,
searchable: false,
selectionProps: rowData => ({
disabled: rowData.name === 'Mehmet',
color: 'primary',
})
}}
onSelectionChange={SelectRows}
localization={localization(props)}
/>
Someone who can tell me how to do it, or where I can find documentation to answer my question?
Pass your custom function to the prop columns.
<MaterialTable
columns={[
{
title: 'Clave',
field: 'clave',
customFilterAndSearch: (term, rowData) => subscribeRemoteRequestsArticle // here
}
]}
options={{
filtering: true
}}
/>

How to add a button to every row in MUI DataGrid

I cant add a button into every row of MUI DataGrid.
I have a MUI DataGrid which I render like this:
<DataGrid rows={rows} columns={columns} pageSize={5} checkboxSelection />
I have added into the columns variable 'actions' column where the button should be. rows are just a a data object I get from the props. how can I add a button into every row (for editing the row)? I have tried mapping the data array but it is not possible to add JSX button into every object of data.
You can add your custom component by overriding GridColDef.renderCell method and return whatever element you want.
The example below displays an action column that renders a single button in each row. When clicking the button, it alerts the current row data in json string:
const columns: GridColDef[] = [
{ field: "id", headerName: "ID", width: 70 },
{
field: "action",
headerName: "Action",
sortable: false,
renderCell: (params) => {
const onClick = (e) => {
e.stopPropagation(); // don't select this row after clicking
const api: GridApi = params.api;
const thisRow: Record<string, GridCellValue> = {};
api
.getAllColumns()
.filter((c) => c.field !== "__check__" && !!c)
.forEach(
(c) => (thisRow[c.field] = params.getValue(params.id, c.field))
);
return alert(JSON.stringify(thisRow, null, 4));
};
return <Button onClick={onClick}>Click</Button>;
}
},
];
Just came across this.
What you need to do is include a renderCell method in your columns array.
const columns = [
{
field: 'col1',
headerName: 'Name 1',
width: 150,
disableClickEventBubbling: true,
},
{
field: 'col2',
headerName: 'Name 2',
width: 300,
disableClickEventBubbling: true,
},
{
field: 'col3',
headerName: 'Name 3',
width: 300,
disableClickEventBubbling: true,
},
{
field: 'col4',
headerName: 'Name 4',
width: 100,
disableClickEventBubbling: true,
},
{
field: 'col5',
headerName: 'Name 5',
width: 150,
***renderCell: renderSummaryDownloadButton,***
disableClickEventBubbling: true,
},
{
field: 'col6',
headerName: 'Name 6',
width: 150,
***renderCell: renderDetailsButton,***
disableClickEventBubbling: true,
},
]
In the above I am rendering a Button inside columns 5 and 6 which will appear on every populated row.
Above that you can have a function which creates and returns a Button from Material-ui.
const renderDetailsButton = (params) => {
return (
<strong>
<Button
variant="contained"
color="primary"
size="small"
style={{ marginLeft: 16 }}
onClick={() => {
parseName(params.row.col6)
}}
>
More Info
</Button>
</strong>
)
}
While #NearHuscarl's response answers the question perfectly, I'd like to post a TypeScript example:
const onClick = () => {
const api: GridApi = params.api;
const fields = api
.getAllColumns()
.map((c) => c.field)
.filter((c) => c !== "__check__" && !!c);
const thisRow: any = {};
fields.forEach((f) => {
thisRow[f] = params.getValue(params.id, f);
});
return alert(JSON.stringify(thisRow, null, 4));
};
return <Button onClick={onClick}>Click</Button>;
Also note, I changed the getValue call. (included the row id)
According to MUI v5 params.getValue method is deprecated and will be removed in the next major version, Instead, you can access the current row data from params.row.
{
field: 'action',
headerName: 'Action',
width: 180,
sortable: false,
disableClickEventBubbling: true,
renderCell: (params) => {
const onClick = (e) => {
const currentRow = params.row;
return alert(JSON.stringify(currentRow, null, 4));
};
return (
<Stack direction="row" spacing={2}>
<Button variant="outlined" color="warning" size="small" onClick={onClick}>Edit</Button>
<Button variant="outlined" color="error" size="small" onClick={onClick}>Delete</Button>
</Stack>
);
},
}
The currently top voted answer is outdated as of v5, because the new GridRowParams interface contains the actual row as a parameter, making the manual filtering from the GridApi unnecessary and unpractical.
Using this with renderCell can be as simple as
const columns: GridColDef[] = [
{ field: "id", headerName: "ID", width: 70 },
{
field: "action",
headerName: "Action",
sortable: false,
renderCell: ({ row }: Partial<GridRowParams>) =>
<Button onClick={() => yourActionFunction(row)}>
Action
</Button>,
},
]
in TypeScript or
const columns = [
{ field: "id", headerName: "ID", width: 70 },
{
field: "action",
headerName: "Action",
sortable: false,
renderCell: ({ row }) =>
<Button onClick={() => yourActionFunction(row)}>
Action
</Button>,
},
]
in plain JavaScript.

Resources