Search code examples
reactjsnext.jsnext.js13mui-x-data-gridmui-x

Reset pagination on sorting - Mui-X DataGrid


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;

Solution

  • Solution (use the useGridApiRef)

    • Step 1: Import the useGridApiRef from @mui/x-data-grid
    • Step 2: Initialise the apiRef (by invoking the useGridApiRef function)
    • Step 3: Use the apiRef (in the DataGrid component)
    • Step 4: Define the restorePaginationState function.
      • apiRef.current.exportState(); will fetch the current state.
      • apiRef.current.restoreState(); will set the new state.
    • Step 5: Invoke the 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;