Search code examples
material-uimui-datatable

React Material Data Grid: Sorting a currency field


I am passing in rows of financial data to a React MUI Data Grid component, however, as a currency symbol exists within the cell data the default sorting function is not working. Is there anyway I can ignore the currency symbol when applying sort?

[
  {id: 0, cpa: '£20', cpl: '£0', revshare: '0%', startDate: '02/03/2022'}
  {id: 1, cpa: '£10', cpl: '£0', revshare: '0%', startDate: '02/02/2022'}
]


<DataGrid
  disableSelectionOnClick
  headerHeight={65}
  rowHeight={70}
  autoHeight
  className={classes.root}
  rows={displayRowData(rowsData)}
  columns={columns}
  />

Solution

  • You can add a custom sortComparator in the columns of your <DataGrid/>. Assuming your currency symbol is always the first character, your cpa column definition would look like this:

      const columns = [
        ...
        {
          field: "cpa",
          headerName: "cpa",
          sortComparator: (a: string, b: string) =>
            Number(a.slice(1)) - Number(b.slice(1)),
        },
        ...
      ];
    

    For more information regarding sorting I would recommend checking out the official documentation.