Row Sorting
Row Sorting
- We can enable/disable the ability to sort a row using the
sortable
property in theColDef
. - The default
sortable
value isfalse
. - Custom sorting can be performed using the
comparator
property, providing a sorting function similar toArray.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:
- Ascending
- Descending
- 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
- Open the challenge on Stackblitz.
- Add the
sortable
property to a column definition. - Override the default sorting order by specifying the
sortingOrder
property on the column definition. - 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>
);
}