Skip to content
+

Data Grid - Server-side row grouping

Lazy-loaded row grouping with server-side data source.

To dynamically load row grouping data from the server, including lazy-loading of children, create a data source and pass the unstable_dataSource prop to the Data Grid, as mentioned in the overview section.

Similar to the tree data, you need to pass some additional properties to enable the data source row grouping feature:

  • getGroupKey(): Returns the group key for the row.
  • getChildrenCount(): Returns the number of children for the row. If the children count is not available for some reason, but there are some children, returns -1.
const customDataSource: GridDataSource = {
  getRows: async (params) => {
    // Fetch the data from the server
  },
  getGroupKey: (row) => {
    // Return the group key for the row, e.g. `name`
    return row.name;
  },
  getChildrenCount: (row) => {
    // Return the number of children for the row
    return row.childrenCount;
  },
};

In addition to groupKeys, the getRows() callback receives a groupFields parameter. This corresponds to the current rowGroupingModel. Use groupFields on the server to group the data for each getRows() call.

const getRows: async (params) => {
  const urlParams = new URLSearchParams({
    // Example: JSON.stringify(['20th Century Fox', 'James Cameron'])
    groupKeys: JSON.stringify(params.groupKeys),
    // Example: JSON.stringify(['company', 'director'])
    groupFields: JSON.stringify(params.groupFields),
  });
  const getRowsResponse = await fetchRows(
    // Server should group the data based on `groupFields` and
    // extract the rows for the nested level based on `groupKeys`
    `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
  );
  return {
    rows: getRowsResponse.rows,
    rowCount: getRowsResponse.rowCount,
  };
}
Press Enter to start editing

Error handling

If an error occurs during a getRows call, the Data Grid displays an error message in the row group cell. unstable_onDataSourceError is also triggered with the error and the fetch params.

This example shows error handling with toast notifications and default error messages in grouping cells. Caching is disabled for simplicity.

Group expansion

The group expansion works similar to the data source tree data. The following demo uses defaultGroupingExpansionDepth='-1' to expand all the groups.

Demo

In the following demo, use the auto generated data based on the Commodities dataset to simulate the server-side row grouping.