I have a Material-UI DataGrid
component, and I want it to reset pagination on sorting (see code below).
import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
const Table: React.FC<Readonly<{}>> = () => {
return (
<div>
<DataGrid
onSortModelChange={() => {
// <------------------------ Here I want to reset pagination on sort
}}
/>
</div>
);
};
export default Table;
useGridApiRef
from @mui/x-data-grid
apiRef
(by invoking the useGridApiRef
function)apiRef
(in the DataGrid
component)restorePaginationState
function.
apiRef.current.exportState();
will fetch the current state.apiRef.current.restoreState();
will set the new state.restorePaginationState
function on onSortModelChange
events.import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { useGridApiRef } from '@mui/x-data-grid'; // <---------- Step 1
const Table: React.FC<Readonly<{}>> = () => {
const apiRef = useGridApiRef(); // <---------- Step 2
const restorePaginationState = () => { // <---------- Step 4
const state = apiRef.current.exportState();
const restoredState = {
...state,
pagination: {
...state.pagination,
paginationModel: {
...state.pagination?.paginationModel,
page: 0, // <-- Set the page to the first page
pageSize: 5, // <-- Specify the pageSize based on the requirements of your grid.
},
},
};
apiRef.current.restoreState(restoredState);
};
return (
<div>
<DataGrid
apiRef={apiRef} // <---------- Step 3
onSortModelChange={() => {
restorePaginationState(); // <---------- Step 5
}}
/>
</div>
);
};
export default Table;