0

Current Behavior Image

Question: Is there a way to not sort the "Total" row while Sorting? Thanks in advance

   <DataGrid
     rows={dataSource}
     columns={dataColumns}
     initialState={{
         sorting: {
             sortModel: [{field: 'Total', sort: 'desc'}]
         }
     }}
     components={{
        Toolbar: CustomToolbar,
        NoRowsOverlay: EmptyRows,
     }}
     getRowId={(row) => row.value}
     filterMode="client"
     filterModel={filterModal}
     onFilterModelChange={(model) => {
          setFilterModal(model);
     }}
   />

Current Behavior: While sorting to descending the "Total" row comes at top

Expected Behavior: I want the "Total" row to be not sorted while sorting the columns

Lokkesh
  • 92
  • 8

3 Answers3

1

Another solution, which would bypass the sorting problem entirely, would be to add the Totals as a Custom footer component instead of a row.

If you want to go Premium, there's also the Aggregation feature, which basically provides a totals row out of the box.

Fitzi
  • 1,641
  • 11
  • 17
0

As for me, the most natural solution would be to control sorting or have some property that will exclude some rows from sorting. But I don't see this in the documentation. You can override the comparator for sorting, but the comparator doesn't receive the full row, only the cell value.

As I see in the Data Grid documentation - you can pin the row to the top or to the bottom. After pinning the row will be excluded from the sorting and filtering.

   <DataGrid
     rows={dataSource.slice(1)}
     pinnedRows={{top: [dataSource[0]]}}
     columns={dataColumns}
     initialState={{
         sorting: {
             sortModel: [{field: 'Total', sort: 'desc'}]
         }
     }}
     components={{
        Toolbar: CustomToolbar,
        NoRowsOverlay: EmptyRows,
     }}
     getRowId={(row) => row.value}
     filterMode="client"
     filterModel={filterModal}
     onFilterModelChange={(model) => {
          setFilterModal(model);
     }}
   />

The problem here is that it will stick to the top or bottom. You can use CSS to override pinning, and you can try to make a more elegant CSS solution that fit your needs, but still, it is kind of a hacky way to solve the issue:

.MuiDataGrid-pinnedRows--top {
  position: relative !important;
  box-shadow: none !important;
}

Also, you can find the code example here look into index.css and demo.js files

0

I got the solution for my question without using Pro as I can use the sortComparator function to do custom sorting

Reference code can be used for a column

headerName: 'Total',
field: 'Total',
type: 'number',
sortComparator: (value1, value2, params1, params2) => {
    if (params1.id === 'Total' || params2.id === 'Total') {
       return 0;
    }
    else return value1 - value2
}

or you can write a function with the reference code and pass it to DataGrid prop sortComparator

<DataGrid 
 sortComporator={...Your Function here}
/>
Lokkesh
  • 92
  • 8