Sorting Feature Guide
Material React Table supports almost any sorting scenario you may have. Client-side sorting is enabled by default, but you can opt to implement your own server-side sorting logic, or even replace the default client-side sorting with your own implementation.
Relevant Props
# | Prop Name | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
|
| MRT Global Filtering Docs | ||
2 |
| ||||
3 |
|
| |||
4 |
| TanStack Table Sorting Docs | |||
5 |
| TanStack Table Sorting Docs | |||
6 |
| TanStack Table Sorting Docs | |||
7 |
| TanStack Table Sorting Docs | |||
8 |
| TanStack Table Sorting Docs | |||
9 |
| TanStack Table Sorting Docs | |||
10 |
| TanStack Table Sorting Docs | |||
Relevant Column Options
Relevant State Options
# | State Option | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
|
| TanStack Table Sorting Docs | ||
Disable Sorting
Sorting can be disabled globally by setting the enableSorting
prop to false
. This will disable sorting for all columns. You can also disable sorting for individual columns by setting the enableSorting
column option to false
.
const columns = [{accessorKey: 'name',header: 'Name',enableSorting: false, // disable sorting for this column},];return (<MaterialReactTablecolumns={columns}data={data}enableSorting={false} //disable sorting for all columns/>);
Default Sorting Features
Client-side sorting is enabled by default. When sorting is toggled on for a column, the table will be sorted by an alphanumeric
sorting algorithm by default.
Multi-Sorting
Multi-sorting is also enabled by default, which means a user can sort by multiple columns at once. This can be accomplished by clicking on a column header while holding down the shift
key. The table will then be sorted by the previously sorted column, and then by the newly clicked column. You can limit the number of columns that can be sorted at once by setting the maxMultiSortColCount
prop, or you can disable multi-sorting entirely by setting the enableMultiSort
prop to false
.
Sort Direction
By default, columns with string
datatypes will sort alphabetically in ascending order, but columns with number
datatypes will sort numerically in descending order. You can change the default sort direction per column by specifying the sortDescFirst
column option to either true
or false
. You can also change the default sort direction globally by setting the sortDescFirst
prop to either true
or false
.
Sorting Functions
By default, Material React Table will use an alphanumeric
sorting function for all columns.
There are 6 built-in sorting functions that you can choose from: alphanumeric
, alphanumericCaseSensitive
, text
, textCaseSensitive
, datetime
, and basic
. You can learn more about these built-in sorting function in the TanStack Table Sorting API docs.
Add Custom Sorting Functions
If none of these sorting functions meet your needs, you can add your own custom sorting functions by specifying more sorting functions in the sortingFns
prop.
<MaterialReactTablecolumns={columns}data={data}sortingFns={{//will add a new sorting function to the list of other sorting functions already availablemyCustomSortingFn: (rowA, rowB, columnId) => // your custom sorting logic}}/>
Change Sorting Function Per Column
You can now choose a sorting function for each column by either passing a string value of the built-in sorting function names to the sortingFn
column option, or by passing a custom sorting function to the sortingFn
column option.
const columns = [{accessorKey: 'name',header: 'Name',sortingFn: 'textCaseSensitive', //use the built-in textCaseSensitive sorting function instead of the default alphanumeric sorting function},{accessorKey: 'age',header: 'Age',//use your own custom sorting function instead of any of the built-in sorting functionssortingFn: (rowA, rowB, columnId) => // your custom sorting logic},];
Manual Server-Side Sorting
If you are working with large data sets, you may want to let your back-end apis handle all of the sorting and pagination processing instead of doing it client-side. You can do this by setting the manualSorting
prop to true
. This will disable the default client-side sorting and pagination features, and will allow you to implement your own sorting and pagination logic.
When
manualSorting
is set totrue
, Material React Table assumes that yourdata
is already sorted by the time you are passing it to the table.
If you need to sort your data in a back-end api, then you will also probably need access to the internal sorting
state from the table. You can do this by managing the sorting
state yourself, and then passing it to the table via the state
prop. You can also pass a callback function to the onSortingChange
prop, which will be called whenever the sorting
state changes internally in the table
const [sorting, setSorting] = useState([]);useEffect(() => {//do something with the sorting state when it changes}, [sorting]);return (<MaterialReactTablecolumns={columns}data={data}manualSortingstate={{ sorting }}onSortingChange={setSorting}/>);
Remote Sorting Example
Here is the full Remote Data example showing how to implement server-side sorting, filtering, and pagination with Material React Table.
First Name | Last Name | Address | State | Phone Number | |
---|---|---|---|---|---|
No records to display |
1import React, { FC, useEffect, useMemo, useState } from 'react';2import MaterialReactTable, { MRT_ColumnDef } from 'material-react-table';3import type {4 ColumnFiltersState,5 PaginationState,6 SortingState,7} from '@tanstack/react-table';89type UserApiResponse = {10 data: Array<User>;11 meta: {12 totalRowCount: number;13 };14};1516type User = {17 firstName: string;18 lastName: string;19 address: string;20 state: string;21 phoneNumber: string;22};2324const Example: FC = () => {25 //data and fetching state26 const [data, setData] = useState<User[]>([]);27 const [isError, setIsError] = useState(false);28 const [isLoading, setIsLoading] = useState(false);29 const [isRefetching, setIsRefetching] = useState(false);30 const [rowCount, setRowCount] = useState(0);3132 //table state33 const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);34 const [globalFilter, setGlobalFilter] = useState('');35 const [sorting, setSorting] = useState<SortingState>([]);36 const [pagination, setPagination] = useState<PaginationState>({37 pageIndex: 0,38 pageSize: 10,39 });4041 //if you want to avoid useEffect, look at the React Query example instead42 useEffect(() => {43 const fetchData = async () => {44 if (!data.length) {45 setIsLoading(true);46 } else {47 setIsRefetching(true);48 }4950 const url = new URL(51 '/api/data',52 process.env.NODE_ENV === 'production'53 ? 'https://www.material-react-table.com'54 : 'http://localhost:3000',55 );56 url.searchParams.set(57 'start',58 `${pagination.pageIndex * pagination.pageSize}`,59 );60 url.searchParams.set('size', `${pagination.pageSize}`);61 url.searchParams.set('filters', JSON.stringify(columnFilters ?? []));62 url.searchParams.set('globalFilter', globalFilter ?? '');63 url.searchParams.set('sorting', JSON.stringify(sorting ?? []));6465 try {66 const response = await fetch(url.href);67 const json = (await response.json()) as UserApiResponse;68 setData(json.data);69 setRowCount(json.meta.totalRowCount);70 } catch (error) {71 setIsError(true);72 console.error(error);73 return;74 }75 setIsError(false);76 setIsLoading(false);77 setIsRefetching(false);78 };79 fetchData();80 // eslint-disable-next-line react-hooks/exhaustive-deps81 }, [82 columnFilters,83 globalFilter,84 pagination.pageIndex,85 pagination.pageSize,86 sorting,87 ]);8889 const columns = useMemo<MRT_ColumnDef<User>[]>(90 () => [91 {92 accessorKey: 'firstName',93 header: 'First Name',94 },95 //column definitions...113 ],114 [],115 );116117 return (118 <MaterialReactTable119 columns={columns}120 data={data}121 enableRowSelection122 getRowId={(row) => row.phoneNumber}123 initialState={{ showColumnFilters: true }}124 manualFiltering125 manualPagination126 manualSorting127 muiToolbarAlertBannerProps={128 isError129 ? {130 color: 'error',131 children: 'Error loading data',132 }133 : undefined134 }135 onColumnFiltersChange={setColumnFilters}136 onGlobalFilterChange={setGlobalFilter}137 onPaginationChange={setPagination}138 onSortingChange={setSorting}139 rowCount={rowCount}140 state={{141 columnFilters,142 globalFilter,143 isLoading,144 pagination,145 showAlertBanner: isError,146 showProgressBars: isRefetching,147 sorting,148 }}149 />150 );151};152153export default Example;154
View Extra Storybook Examples