Data Grid - Sorting
Easily sort your rows based on one or several criteria.
Sorting is enabled by default to the data grid users and works out of the box without any explicit configuration. Users can set a sorting rule simply by clicking on a column header. Following clicks change the column's sorting direction. You can see the applied direction on the header's arrow indicator.
Single and multi-sorting
Multi-sorting
The following demo lets you sort the rows according to several criteria at the same time.
Hold down the Ctrl or Shift (use ⌘ Command on macOS) key while clicking the column header.
Pass sorting rules to the data grid
Structure of the model
The sort model is a list of sorting items. Each item represents a sorting rule and is composed of several elements:
sortingItem.field
: the field on which the rule applies.sortingItem.sort
: the direction of the sorting ('asc'
,'desc'
,null
orundefined
). Ifnull
orundefined
, the rule doesn't apply.
Initialize the sort model
Sorting is enabled by default to the user.
But if you want to set an initial sorting order, simply provide the model to the initialState
prop.
<DataGrid
initialState={{
sorting: {
sortModel: [{ field: 'rating', sort: 'desc' }],
},
}}
/>
Controlled sort model
Use the sortModel
prop to control the state of the sorting rules.
You can use the onSortModelChange
prop to listen to changes in the sorting rules and update the prop accordingly.
Disable the sorting
For all columns
Sorting is enabled by default, but you can easily disable this feature by setting the disableColumnSorting
prop.
<DataGrid disableColumnSorting />
For some columns
By default, all columns are sortable.
To disable sorting on a column, set the sortable
property of GridColDef
to false
.
In the following demo, the user cannot sort the rating column from the UI.
<DataGrid columns={[...columns, { field: 'rating', sortable: false }]} />
Sorting non-sortable columns programmatically
The columns with colDef.sortable
set to false
are not sortable from the grid UI but could still be sorted programmatically. To add a sort rule to such a column, you could initialize the sortModel
, use the sortModel
prop, or use the API methods sortColumn
or setSortModel
.
In the following demo, the firstName
column is not sortable by the default grid UI, but it is sorted programmatically by a custom built UI.
Custom comparator
A comparator determines how two cell values should be sorted.
Each column type comes with a default comparator method. You can re-use them by importing the following functions:
gridStringOrNumberComparator
(used by thestring
andsingleSelect
columns)gridNumberComparator
(used by thenumber
andboolean
columns)gridDateComparator
(used by thedate
anddate-time
columns)
To extend or modify this behavior in a specific column, you can pass in a custom comparator, and override the sortComparator
property of the GridColDef
interface.
Create a comparator from scratch
In the following demo, the "Created on" column sorting is based on the day of the month of the createdOn
field.
It is a fully custom sorting comparator.
Combine built-in comparators
In the following demo, the "Name" column combines the name
and isAdmin
fields.
The sorting is based on isAdmin
and then on name
, if necessary. It re-uses the built-in sorting comparator.
Asymmetric comparator
The Data Grid considers the sortComparator
function symmetric, automatically reversing the return value for descending sorting by multiplying it by -1
.
While this is sufficient for most use cases, it is possible to define an asymmetric comparator using the getSortComparator
function – it receives the sorting direction as an argument and returns a comparator function.
In the demo below, the getSortComparator
function is used in the "Quantity" column to keep the null
values at the bottom when sorting is applied (regardless of the sorting direction):
Custom sort order
By default, the sort order cycles between these three different modes:
const sortingOrder = ['asc', 'desc', null];
In practice, when you click a column that is not sorted, it will sort ascending (asc
).
The next click will make it sort descending (desc
). Another click will remove the sort (null
), reverting to the order that the data was provided in.
For all columns
The default sort order can be overridden for all columns with the sortingOrder
prop.
In the following demo, columns are only sortable in descending or ascending order.
Per column
Sort order can be configured (and overridden) on a per-column basis by setting the sortingOrder
property of the GridColDef
interface:
const columns: GridColDef = [
{ field: 'rating', sortingOrder: ['desc', 'asc', null] },
];
Server-side sorting
Sorting can be run server-side by setting the sortingMode
prop to server
, and implementing the onSortModelChange
handler.
applySorting()
Applies the current sort model to the rows.
Signature:
applySorting: () => void
getRowIdFromRowIndex()
Gets the GridRowId
of a row at a specific index. The index is based on the sorted but unfiltered row list.
Signature:
getRowIdFromRowIndex: (index: number) => GridRowId
getSortedRowIds()
Returns all row ids sorted according to the active sort model.
Signature:
getSortedRowIds: () => GridRowId[]
getSortedRows()
Returns all rows sorted according to the active sort model.
Signature:
getSortedRows: () => GridRowModel[]
getSortModel()
Returns the sort model currently applied to the grid.
Signature:
getSortModel: () => GridSortModel
setSortModel()
Updates the sort model and triggers the sorting of rows.
Signature:
setSortModel: (model: GridSortModel) => void
sortColumn()
Sorts a column.
Signature:
sortColumn: (field: GridColDef['field'], direction?: GridSortDirection, allowMultipleSorting?: boolean) => void
gridSortModelSelector
Signature:
gridSortModelSelector: (apiRef: GridApiRef) => GridSortModel
// or
gridSortModelSelector: (state: GridState, instanceId?: number) => GridSortModel
Example
gridSortModelSelector(apiRef)
// or
gridSortModelSelector(state, apiRef.current.instanceId)
gridSortedRowEntriesSelector
Signature:
gridSortedRowEntriesSelector: (apiRef: GridApiRef) => { id: GridRowId; model: GridValidRowModel }[]
// or
gridSortedRowEntriesSelector: (state: GridState, instanceId?: number) => { id: GridRowId; model: GridValidRowModel }[]
Example
gridSortedRowEntriesSelector(apiRef)
// or
gridSortedRowEntriesSelector(state, apiRef.current.instanceId)
gridSortedRowIdsSelector
Signature:
gridSortedRowIdsSelector: (apiRef: GridApiRef) => GridRowId[]
// or
gridSortedRowIdsSelector: (state: GridState, instanceId?: number) => GridRowId[]
Example
gridSortedRowIdsSelector(apiRef)
// or
gridSortedRowIdsSelector(state, apiRef.current.instanceId)
More information about the selectors and how to use them on the dedicated page