MRT logoMantine React Table

On This Page

    Sorting Feature Guide

    Mantine 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 Table Options

    #
    Prop Name
    Type
    Default Value
    More Info Links
    1booleantrueMRT Global Filtering Docs
    2boolean
    3booleantrue
    4booleantrue
    5(table: Table<TData>) => () => RowModel<TData>TanStack Table Sorting Docs
    6(e: unknown) => booleanTanStack Table Sorting Docs
    7booleanTanStack Table Sorting Docs
    8numberTanStack Table Sorting Docs
    9OnChangeFn<SortingState>TanStack Table Sorting Docs
    10booleanTanStack Table Sorting Docs
    11Record<string, SortingFn>TanStack Table Sorting Docs

    Relevant Column Options

    #
    Column Option
    Type
    Default Value
    More Info Links
    1booleantrue
    2boolean
    3booleanfalse
    4boolean
    5false | 1 | -1
    6SortingFnOption

    Relevant State Options

    #
    State Option
    Type
    Default Value
    More Info Links
    1Array<{ id: string, desc: boolean }>[]TanStack Table Sorting Docs

    Disable Sorting

    Sorting can be disabled globally by setting the enableSorting table option 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
      },
    ];
    
    const table = useMantineReactTable({
      columns,
      data,
      enableSorting: false, //disable sorting for all columns
    });
    
    return <MantineReactTable table={table} />;

    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 table options.

    const table = useMantineReactTable({
      columns,
      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 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. Or if you want multi-sorting to be the default click behavior without the need to hold shift, you can set the isMultiSortEvent table option to () => true.

    const table = useMantineReactTable({
      columns,
      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 table option, or you can disable multi-sorting entirely by setting the enableMultiSort table option 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 table option to false.

    const table = useMantineReactTable({
      columns,
      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 table option to either true or false.

    First Name
    Last Name
    City
    2
    State
    1
    Salary
    VioletDoeSan FranciscoCalifornia100000
    MasonZhangSacramentoCalifornia100000
    LebronJamesIndianapolisIndiana40000
    JosephWilliamsValentineNebraska100000
    AllisonBrownOmahaNebraska10000
    HarrySmithHickmanNebraska20000
    SallyWilliamsonAllianceNebraska30000
    NoahBrownToledoOhio50000
    MichaelMcGinnisHarrisonburgVirginia150000

    Rows per page

    1-9 of 9

    import '@mantine/core/styles.css';
    import '@mantine/dates/styles.css'; //if using mantine date picker features
    import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
    import { MantineReactTable, type MRT_ColumnDef } from 'mantine-react-table';
    import { data, type Person } from './makeData';
    import { Button } from '@mantine/core';
    
    const columns: MRT_ColumnDef<Person>[] = [
      {
        accessorKey: 'firstName',
        header: 'First Name',
        sortDescFirst: false, //sort first name in ascending order by default on first sort click (default for non-numeric columns)
      },
    
      {
        accessorKey: 'lastName',
        header: 'Last Name',
      },
      {
        accessorKey: 'city',
        header: 'City',
      },
      {
        accessorKey: 'state',
        header: 'State',
      },
    
      {
        accessorKey: 'salary',
        header: 'Salary',
        sortDescFirst: true, //sort salary in descending order by default on first sort click (default for numeric columns)
      },
    ];
    
    const Example = () => {
      return (
        <MantineReactTable
          columns={columns}
          data={data}
          isMultiSortEvent={() => true} //now no need to hold `shift` key to multi-sort
          maxMultiSortColCount={3} //prevent more than 3 columns from being sorted at once
          initialState={{
            sorting: [
              { id: 'state', desc: false }, //sort by state in ascending order by default
              { id: 'city', desc: true }, //then sort by city in descending order by default
            ],
          }}
          renderTopToolbarCustomActions={({ table }) => (
            <Button onClick={() => table.resetSorting(true)}>
              Clear All Sorting
            </Button>
          )}
        />
      );
    };
    
    export default Example;

    Sorting Functions

    By default, Mantine 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 table option.

    const table = useMantineReactTable({
      columns,
      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 table option 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, Mantine 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 table option. You can also pass a callback function to the onSortingChange table option, 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]);
    
    const table = useMantineReactTable({
      columns,
      data,
      manualSorting: true,
      state: { sorting },
      onSortingChange: setSorting,
    });
    
    return <MantineReactTable table={table} />;

    Remote Sorting Example

    Here is the full Remote Data example showing how to implement server-side sorting, filtering, and pagination with Mantine React Table.

    First Name
    Last Name
    Address
    State
    Phone Number

    No records to display

    Rows per page

    0-0 of 0

    import '@mantine/core/styles.css';
    import '@mantine/dates/styles.css'; //if using mantine date picker features
    import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
    import { useEffect, useMemo, useState } from 'react';
    import {
      MantineReactTable,
      useMantineReactTable,
      type MRT_ColumnDef,
      type MRT_ColumnFiltersState,
      type MRT_PaginationState,
      type MRT_SortingState,
    } from 'mantine-react-table';
    
    type UserApiResponse = {
      data: Array<User>;
      meta: {
        totalRowCount: number;
      };
    };
    
    type User = {
      firstName: string;
      lastName: string;
      address: string;
      state: string;
      phoneNumber: string;
    };
    
    const Example = () => {
      //data and fetching state
      const [data, setData] = useState<User[]>([]);
      const [isError, setIsError] = useState(false);
      const [isLoading, setIsLoading] = useState(false);
      const [isRefetching, setIsRefetching] = useState(false);
      const [rowCount, setRowCount] = useState(0);
    
      //table state
      const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>(
        [],
      );
      const [globalFilter, setGlobalFilter] = useState('');
      const [sorting, setSorting] = useState<MRT_SortingState>([]);
      const [pagination, setPagination] = useState<MRT_PaginationState>({
        pageIndex: 0,
        pageSize: 10,
      });
    
      //if you want to avoid useEffect, look at the React Query example instead
      useEffect(() => {
        const fetchData = async () => {
          if (!data.length) {
            setIsLoading(true);
          } else {
            setIsRefetching(true);
          }
    
          const url = new URL(
            '/api/data',
            process.env.NODE_ENV === 'production'
              ? 'https://www.mantine-react-table.com'
              : 'http://localhost:3001',
          );
          url.searchParams.set(
            'start',
            `${pagination.pageIndex * pagination.pageSize}`,
          );
          url.searchParams.set('size', `${pagination.pageSize}`);
          url.searchParams.set('filters', JSON.stringify(columnFilters ?? []));
          url.searchParams.set('globalFilter', globalFilter ?? '');
          url.searchParams.set('sorting', JSON.stringify(sorting ?? []));
    
          try {
            const response = await fetch(url.href);
            const json = (await response.json()) as UserApiResponse;
            setData(json.data);
            setRowCount(json.meta.totalRowCount);
          } catch (error) {
            setIsError(true);
            console.error(error);
            return;
          }
          setIsError(false);
          setIsLoading(false);
          setIsRefetching(false);
        };
        fetchData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [
        columnFilters, //refetch when column filters change
        globalFilter, //refetch when global filter changes
        pagination.pageIndex, //refetch when page index changes
        pagination.pageSize, //refetch when page size changes
        sorting, //refetch when sorting changes
      ]);
    
      const columns = useMemo<MRT_ColumnDef<User>[]>(
        () => [
          {
            accessorKey: 'firstName',
            header: 'First Name',
          },
    
          {
            accessorKey: 'lastName',
            header: 'Last Name',
          },
          {
            accessorKey: 'address',
            header: 'Address',
          },
          {
            accessorKey: 'state',
            header: 'State',
          },
          {
            accessorKey: 'phoneNumber',
            header: 'Phone Number',
          },
        ],
        [],
      );
    
      const table = useMantineReactTable({
        columns,
        data,
        enableRowSelection: true,
        getRowId: (row) => row.phoneNumber,
        initialState: { showColumnFilters: true },
        manualFiltering: true,
        manualPagination: true,
        manualSorting: true,
        rowCount,
        onColumnFiltersChange: setColumnFilters,
        onGlobalFilterChange: setGlobalFilter,
        onPaginationChange: setPagination,
        onSortingChange: setSorting,
        state: {
          columnFilters,
          globalFilter,
          isLoading,
          pagination,
          showAlertBanner: isError,
          showProgressBars: isRefetching,
          sorting,
        },
        mantineToolbarAlertBannerProps: isError
          ? { color: 'red', children: 'Error loading data' }
          : undefined,
      });
    
      return <MantineReactTable table={table} />;
    };
    
    export default Example;

    View Extra Storybook Examples