MRT logoMaterial React Table

On This Page

    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

    1
    boolean
    true
    MRT Global Filtering Docs
    2
    boolean
    3
    boolean
    true
    4
    (table: Table<TData>) => () => RowModel<TData>
    TanStack Table Sorting Docs
    5
    (e: unknown) => boolean
    TanStack Table Sorting Docs
    6
    boolean
    TanStack Table Sorting Docs
    7
    number
    TanStack Table Sorting Docs
    8
    OnChangeFn<SortingState>
    TanStack Table Sorting Docs
    9
    boolean
    TanStack Table Sorting Docs
    10
    Record<string, SortingFn>
    TanStack Table Sorting Docs

    Relevant Column Options

    1
    boolean
    true
    2
    boolean
    3
    boolean
    false
    4
    boolean
    5
    false | 1 | -1
    6
    SortingFnOption

    Relevant State Options

    1
    Array<{ id: string, desc: boolean }>
    []
    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 (
    <MaterialReactTable
    columns={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.

    <MaterialReactTable
    columns={columns}
    data={data}
    sortingFns={{
    //will add a new sorting function to the list of other sorting functions already available
    myCustomSortingFn: (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 functions
    sortingFn: (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 to true, Material React Table assumes that your data 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 (
    <MaterialReactTable
    columns={columns}
    data={data}
    manualSorting
    state={{ 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.


    Demo

    Open StackblitzOpen Code SandboxOpen on GitHub

    No records to display

    Rows per page

    0-0 of 0

    Source Code

    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';
    8
    9type UserApiResponse = {
    10 data: Array<User>;
    11 meta: {
    12 totalRowCount: number;
    13 };
    14};
    15
    16type User = {
    17 firstName: string;
    18 lastName: string;
    19 address: string;
    20 state: string;
    21 phoneNumber: string;
    22};
    23
    24const Example: FC = () => {
    25 //data and fetching state
    26 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);
    31
    32 //table state
    33 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 });
    40
    41 //if you want to avoid useEffect, look at the React Query example instead
    42 useEffect(() => {
    43 const fetchData = async () => {
    44 if (!data.length) {
    45 setIsLoading(true);
    46 } else {
    47 setIsRefetching(true);
    48 }
    49
    50 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 ?? []));
    64
    65 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-deps
    81 }, [
    82 columnFilters,
    83 globalFilter,
    84 pagination.pageIndex,
    85 pagination.pageSize,
    86 sorting,
    87 ]);
    88
    89 const columns = useMemo<MRT_ColumnDef<User>[]>(
    90 () => [
    91 {
    92 accessorKey: 'firstName',
    93 header: 'First Name',
    94 },
    95 //column definitions...
    113 ],
    114 [],
    115 );
    116
    117 return (
    118 <MaterialReactTable
    119 columns={columns}
    120 data={data}
    121 enableRowSelection
    122 getRowId={(row) => row.phoneNumber}
    123 initialState={{ showColumnFilters: true }}
    124 manualFiltering
    125 manualPagination
    126 manualSorting
    127 muiToolbarAlertBannerProps={
    128 isError
    129 ? {
    130 color: 'error',
    131 children: 'Error loading data',
    132 }
    133 : undefined
    134 }
    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};
    152
    153export default Example;
    154

    View Extra Storybook Examples