Search code examples
reactjsmaterial-uimui-x-data-grid

MUI DataGrid sorting - is it possible to consider multiple columns when defining a default sortModel?


I have a data model that contains 3 different date fields (estimateDue, workStartDue, workEndDue). I have a requirement that states that, for each row, the default sorting should consider all 3 date fields, identify the soonest and use that value for the sorting for that row.

So, for example, if a the estimateDue value is soonest, then that value should be used, but for another row workStartDue might be soonest, so that value should be used. These values should then be used for sorting the rows.

Is this possible? I've read as much as I can find about defining the default sortModel, but have been unable to find anything suggesting how this could be done.

Many thanks!


Solution

  • The solution to this is to add a column where you derive its value from other columns. Then you can sort on that new column. My example is leveraging maturityDate and dateCreated in the demo data from the docs, but you could apply the same idea to your 3 dates.

      {
        field: "earliestDate",
        headerName: "Earliest Date",
        type: "date",
        width: 150,
        valueGetter: (params) => {
          if (params.row.maturityDate < params.row.dateCreated) {
            return params.row.maturityDate;
          }
          return params.row.dateCreated;
        }
      }
    

    Edit derived sort