LiveLoveApp logo

Row Sorting

Row Sorting

  • We can enable/disable the ability to sort a row using the sortable property in the ColDef.
  • The default sortable value is false.
  • Custom sorting can be performed using the comparator property, providing a sorting function similar to Array.prototype.sort().

Let's look an example:

export default function Grid() {
  const [columnDefs] = useState<ColDef<RowData>[]>([
    {
      headerName: 'Name',
      field: 'name',
      sortable: true,
    },
    { headerName: 'Color', field: 'color' },
  ]);
  const [rowData] = useState<RowData[]>(data.products);

  return (
    <div className="ag-theme-quartz-auto-dark">
      <AgGridReact columnDefs={columnDefs} rowData={rowData}></AgGridReact>
    </div>
  );
}

Sorting Order

By default the sorting order is set to:

  1. Ascending
  2. Descending
  3. None

We can specify the sortingOrder column definition property to override the default behavior.

Let's look at an example of specifying custom sorting order:

export default function Grid() {
  const [columnDefs] = useState<ColDef<RowData>[]>([
    {
      headerName: 'Name',
      field: 'name',
      sortable: true,
      sortingOrder: ['asc', 'desc'],
    },
    { headerName: 'Color', field: 'color' },
  ]);
  const [rowData] = useState<RowData[]>(data.products);
}

Multi-column sorting

Users can sort multiple columns by holding the Shift-key and clicking on the column headers.

We can specify the multiSortKey table option to override the behavior.

export default function Grid() {
  return (
    <div className="ag-theme-quartz-auto-dark">
      <AgGridReact
        columnDefs={columnDefs}
        rowData={rowData}
        multiSortKey="ctrl"
      ></AgGridReact>
    </div>
  );
}

This sets the sorting key to be the Command (macOS) or Ctrl (Windows) key.

Exercise

  1. Open the challenge on Stackblitz.
  2. Add the sortable property to a column definition.
  3. Override the default sorting order by specifying the sortingOrder property on the column definition.
  4. Override the default multi-column sorting key by specifying the multiSortKey prop on the <AgGridReact> component.

Solution

export default function Grid() {
  const [columnDefs] = useState<ColDef<RowData>[]>([
    {
      headerName: 'Name',
      field: 'name',
      sortable: true,
      sortingOrder: ['asc', 'desc'],
    },
    { headerName: 'Color', field: 'color' },
  ]);
  const [rowData] = useState<RowData[]>(data.products);

  return (
    <div className="ag-theme-quartz-auto-dark">
      <AgGridReact
        columnDefs={columnDefs}
        rowData={rowData}
        multiSortKey="ctrl"
      ></AgGridReact>
    </div>
  );
}