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, { useEffect, useMemo, useState } from 'react';
    2import MaterialReactTable, {
    3 MRT_ColumnDef,
    4 MRT_ColumnFiltersState,
    5 MRT_PaginationState,
    6 MRT_SortingState,
    7} from 'material-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 = () => {
    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<MRT_ColumnFiltersState>(
    34 [],
    35 );
    36 const [globalFilter, setGlobalFilter] = useState('');
    37 const [sorting, setSorting] = useState<MRT_SortingState>([]);
    38 const [pagination, setPagination] = useState<MRT_PaginationState>({
    39 pageIndex: 0,
    40 pageSize: 10,
    41 });
    42
    43 //if you want to avoid useEffect, look at the React Query example instead
    44 useEffect(() => {
    45 const fetchData = async () => {
    46 if (!data.length) {
    47 setIsLoading(true);
    48 } else {
    49 setIsRefetching(true);
    50 }
    51
    52 const url = new URL(
    53 '/api/data',
    54 process.env.NODE_ENV === 'production'
    55 ? 'https://www.material-react-table.com'
    56 : 'http://localhost:3000',
    57 );
    58 url.searchParams.set(
    59 'start',
    60 `${pagination.pageIndex * pagination.pageSize}`,
    61 );
    62 url.searchParams.set('size', `${pagination.pageSize}`);
    63 url.searchParams.set('filters', JSON.stringify(columnFilters ?? []));
    64 url.searchParams.set('globalFilter', globalFilter ?? '');
    65 url.searchParams.set('sorting', JSON.stringify(sorting ?? []));
    66
    67 try {
    68 const response = await fetch(url.href);
    69 const json = (await response.json()) as UserApiResponse;
    70 setData(json.data);
    71 setRowCount(json.meta.totalRowCount);
    72 } catch (error) {
    73 setIsError(true);
    74 console.error(error);
    75 return;
    76 }
    77 setIsError(false);
    78 setIsLoading(false);
    79 setIsRefetching(false);
    80 };
    81 fetchData();
    82 // eslint-disable-next-line react-hooks/exhaustive-deps
    83 }, [
    84 columnFilters,
    85 globalFilter,
    86 pagination.pageIndex,
    87 pagination.pageSize,
    88 sorting,
    89 ]);
    90
    91 const columns = useMemo<MRT_ColumnDef<User>[]>(
    92 () => [
    93 {
    94 accessorKey: 'firstName',
    95 header: 'First Name',
    96 },
    97 //column definitions...
    115 ],
    116 [],
    117 );
    118
    119 return (
    120 <MaterialReactTable
    121 columns={columns}
    122 data={data}
    123 enableRowSelection
    124 getRowId={(row) => row.phoneNumber}
    125 initialState={{ showColumnFilters: true }}
    126 manualFiltering
    127 manualPagination
    128 manualSorting
    129 muiToolbarAlertBannerProps={
    130 isError
    131 ? {
    132 color: 'error',
    133 children: 'Error loading data',
    134 }
    135 : undefined
    136 }
    137 onColumnFiltersChange={setColumnFilters}
    138 onGlobalFilterChange={setGlobalFilter}
    139 onPaginationChange={setPagination}
    140 onSortingChange={setSorting}
    141 rowCount={rowCount}
    142 state={{
    143 columnFilters,
    144 globalFilter,
    145 isLoading,
    146 pagination,
    147 showAlertBanner: isError,
    148 showProgressBars: isRefetching,
    149 sorting,
    150 }}
    151 />
    152 );
    153};
    154
    155export default Example;
    156

    View Extra Storybook Examples