skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search