MRT logoMaterial React Table

Legacy V1 Docs
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
    boolean
    true
    5
    (table: Table<TData>) => () => RowModel<TData>
    TanStack Table Sorting Docs
    6
    (e: unknown) => boolean
    TanStack Table Sorting Docs
    7
    boolean
    TanStack Table Sorting Docs
    8
    number
    TanStack Table Sorting Docs
    9
    OnChangeFn<SortingState>
    TanStack Table Sorting Docs
    10
    boolean
    TanStack Table Sorting Docs
    11
    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
    />
    );

    Initial/Default Sorting

    You can sort by a column or multiple columns by default by setting the sorting state option in either the initialState or state props.

    <MaterialReactTable
    columns={columns}
    data={data}
    initialState={{
    sorting: [
    {
    id: 'age', //sort by age by default on page load
    desc: true,
    },
    {
    id: 'lastName', //then sort by lastName if age is the same
    desc: true,
    },
    ],
    }}
    />

    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 you can sort by multiple columns at once. You can do this by clicking on a column header while holding down the shift key. The table will then be sorted by the previously sorted column, followed by the newly clicked column. Alternatively, if you want multi-sorting to be the default click behavior without the need to hold shift, you can set the isMultiSortEvent prop to () => true.

    <MaterialReactTable
    columns={columns}
    data={data}
    isMultiSortEvent={() => true} //multi-sorting will be the default click behavior without the need to hold shift
    />

    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.

    Sorting Removal

    By default, users can remove a sort on a column by clicking through the sort direction options or selecting "Clear Sort" from the column actions menu. You can disable this feature by setting the enableSortingRemoval prop to false.

    <MaterialReactTable
    columns={columns}
    data={data}
    enableSortingRemoval={false} //users will not be able to remove a sort on a column
    />

    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.


    Demo

    Open StackblitzOpen Code SandboxOpen on GitHub
    VioletDoeSan FranciscoCalifornia100000
    MasonZhangSacramentoCalifornia100000
    LebronJamesIndianapolisIndiana40000
    JosephWilliamsValentineNebraska100000
    AllisonBrownOmahaNebraska10000
    HarrySmithHickmanNebraska20000
    SallyWilliamsonAllianceNebraska30000
    NoahBrownToledoOhio50000
    MichaelMcGinnisHarrisonburgVirginia150000

    Rows per page

    1-9 of 9

    Source Code

    1import React from 'react';
    2import { MaterialReactTable, type MRT_ColumnDef } from 'material-react-table';
    3import { data, type Person } from './makeData';
    4import { Button } from '@mui/material';
    5
    6const columns: MRT_ColumnDef<Person>[] = [
    7 {
    8 accessorKey: 'firstName',
    9 header: 'First Name',
    10 sortDescFirst: false, //sort first name in ascending order by default on first sort click (default for non-numeric columns)
    11 },
    12 //column definitions...
    26 {
    27 accessorKey: 'salary',
    28 header: 'Salary',
    29 sortDescFirst: true, //sort salary in descending order by default on first sort click (default for numeric columns)
    30 },
    31];
    32
    33const Example = () => {
    34 return (
    35 <MaterialReactTable
    36 columns={columns}
    37 data={data}
    38 isMultiSortEvent={() => true} //now no need to hold `shift` key to multi-sort
    39 maxMultiSortColCount={3} //prevent more than 3 columns from being sorted at once
    40 initialState={{
    41 sorting: [
    42 { id: 'state', desc: false }, //sort by state in ascending order by default
    43 { id: 'city', desc: true }, //then sort by city in descending order by default
    44 ],
    45 }}
    46 renderTopToolbarCustomActions={({ table }) => (
    47 <Button onClick={() => table.resetSorting(true)}>
    48 Clear All Sorting
    49 </Button>
    50 )}
    51 />
    52 );
    53};
    54
    55export default Example;
    56

    Sorting Functions

    By default, Material React Table will use an alphanumeric sorting function for all columns.

    There are six built-in sorting functions you can choose from: alphanumeric, alphanumericCaseSensitive, text, textCaseSensitive, datetime, and basic. You can learn more about these built-in sorting functions 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 let you 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

    No records to display

    Rows per page

    0-0 of 0

    Source Code

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

    View Extra Storybook Examples