Examples › Sorting

Name
Street address
City
State
Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburghCA
Cummerata - Kuhlman6389 Dicki StreamSouth GateNH
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburghKS
Feest, Bogan and Herzog21716 Ratke DriveStromanportWY
Goldner, Rohan and Lehner632 Broadway AvenueNorth LouieWY
Goyette Inc8873 Mertz RapidDorthysideID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Kling - McLaughlin8346 Kertzmann SquareSouth JoesphID
Rau - O'Hara7508 Lansdowne RoadShieldsboroughMI
Runte Inc2996 Ronny MountMcAllenMA
Shanahan, Robel and Beier378 Berta CrescentWest GerryKS
Tillman - Jacobi57918 Gwendolyn CirclesSheridanportMI
No records

To enable sorting, you’ll have to:

  • add a sortable: true property to each column that should be sortable;
  • set the DataTable sortStatus property to an object describing the current sort status (the column accessor and the sort direction, 'asc' or 'desc');
  • provide an onSortStatusChange handler, which is invoked with the new sort status when the user clicks a sortable column header.
'use client';

import { DataTable, type DataTableSortStatus } from 'mantine-datatable';
import sortBy from 'lodash/sortBy';
import { useEffect, useState } from 'react';
import { type Company, companies } from '~/data';

export default function SortingExample() {
  const [sortStatus, setSortStatus] = useState<DataTableSortStatus<Company>>({
    columnAccessor: 'name',
    direction: 'asc',
  });
  const [records, setRecords] = useState(sortBy(companies, 'name'));

  useEffect(() => {
    const data = sortBy(companies, sortStatus.columnAccessor) as Company[];
    setRecords(sortStatus.direction === 'desc' ? data.reverse() : data);
  }, [sortStatus]);

  return (
    <DataTable
      withTableBorder
      withColumnBorders
      records={records}
      columns={[
        { accessor: 'name', width: '40%', sortable: true },
        { accessor: 'streetAddress', width: '60%' },
        { accessor: 'city', width: 160, sortable: true },
        { accessor: 'state', textAlign: 'right', sortable: true },
      ]}
      sortStatus={sortStatus}
      onSortStatusChange={setSortStatus}
    />
  );
}

Sorting by a different key

Sometimes the value you want to sort by is not the one designated by the column accessor — for instance, when a column renders a value computed from several record properties. In this case, set the column’s sortKey property; it will be included in the sort status object received by onSortStatusChange, so you can use it in your sorting logic.
In the example below, the Name column renders the employee’s full name, but is sorted by last name. Notice that dot-notation accessors such as department.name can be sortable too:

'use client';

import { DataTable, type DataTableSortStatus } from 'mantine-datatable';
import dayjs from 'dayjs';
import sortBy from 'lodash/sortBy';
import { useMemo, useState } from 'react';
import { type Employee, employees } from '~/data';

const initialRecords = employees.slice(0, 50);

export default function SortingExampleSortKey() {
  const [sortStatus, setSortStatus] = useState<DataTableSortStatus<Employee>>({
    columnAccessor: 'name',
    sortKey: 'lastName',
    direction: 'asc',
  });

  const records = useMemo(() => {
    // 👇 use the sort key if present, otherwise fall back to the column accessor
    const data = sortBy(initialRecords, sortStatus.sortKey ?? sortStatus.columnAccessor);
    return sortStatus.direction === 'desc' ? data.reverse() : data;
  }, [sortStatus]);

  return (
    <DataTable
      // other props...
      records={records}
      columns={[
        {
          accessor: 'name',
          render: ({ firstName, lastName }) => `${firstName} ${lastName}`,
          sortable: true,
          sortKey: 'lastName', // 👈 sort by last name
        },
        // 👇 dot-notation accessors work too
        { accessor: 'department.name', title: 'Department', sortable: true },
        {
          accessor: 'birthDate',
          textAlign: 'right',
          render: ({ birthDate }) => dayjs(birthDate).format('MMM D YYYY'),
          sortable: true,
        },
      ]}
      sortStatus={sortStatus}
      onSortStatusChange={setSortStatus}
    />
  );
}
Name
Department
Birth date
Martin BahringerBeautyMay 26 1945
Greg BaileyHomeJan 2 1967
Emily BartolettiAutomotiveJan 5 1968
Erick BruenElectronicsSep 26 1952
Gloria ColeHomeDec 9 1996
Hattie CollierOutdoorsApr 14 1954
Abraham DooleyJeweleryOct 5 1956
Eugene FeestKidsFeb 20 1954
Dianna Gislason-LeschGamesMay 29 1966
Felicia GleasonShoesMar 9 1977
Ruby GrahamSportsMay 30 1970
Debbie HagenesClothingJan 24 1968
Reginald HagenesIndustrialMay 19 1950
Lindsey HeidenreichGamesJul 13 1997
Beverly HellerBeautyNov 29 2001
Jerald HowellIndustrialMay 21 1950
Carlton JenkinsSportsJun 7 1943
Jonathan Keebler-CronaMusicOct 22 2002
Alison KlingJeweleryJan 27 1997
Gregg KutchMoviesNov 28 1986
Faith LangworthClothingNov 27 1983
Alicia LeannonSportsDec 27 2005
Kim LebsackJeweleryJun 11 1970
Myron LemkeShoesSep 27 1978
Jacqueline LeschGamesJul 22 1978
Elsa MarvinBooksOct 7 1982
Lionel McCulloughKidsFeb 23 1986
Ellis MillerElectronicsMay 24 1950
Boyd MohrJeweleryJun 18 1951
Clifford OberbrunnerAutomotiveMar 6 1979
Adam PagacBooksDec 4 1961
Anne PowlowskiMusicJan 26 1957
Mamie RaynorGroceryNov 5 1992
Delores ReynoldsIndustrialJun 4 2004
Kathleen RueckerComputersDec 19 1943
Earl RyanBeautyJan 8 1961
Louis SchambergerToolsSep 7 1994
Bernice SchinnerGardenDec 23 2005
Kathleen SpinkaJeweleryFeb 28 1947
Felix StokesKidsMar 21 1984
Renee TillmanIndustrialNov 24 1953
Shelia TurcotteMusicJul 22 1959
Erica VolkmanToysJan 29 1955
Richard WatsicaOutdoorsJun 10 1971
Rolando WeissnatHomeApr 25 1951
Lance WiegandGroceryJul 12 1966
Linda WittingBabyMay 16 1965
Nathan WolfGamesJul 2 1998
Alfredo ZemlakGamesNov 12 1988
Sue ZiemeBooksSep 12 1960
No records

Custom sort icons

To use custom sort icons, pass an object with sorted and unsorted keys to the sortIcons property. The sorted icon should point up; it will be flipped vertically automatically when the sort direction is descending:

'use client';

import type { DataTableSortStatus } from 'mantine-datatable';
import { DataTable } from 'mantine-datatable';
import { IconChevronUp, IconSelector } from '@tabler/icons-react';
import sortBy from 'lodash/sortBy';
import { useEffect, useState } from 'react';
import { type Company, companies } from '~/data';

export default function SortingExampleCustomIcons() {
  const [sortStatus, setSortStatus] = useState<DataTableSortStatus<Company>>({
    columnAccessor: 'name',
    direction: 'asc',
  });
  const [records, setRecords] = useState(sortBy(companies, 'name'));

  useEffect(() => {
    const data = sortBy(companies, sortStatus.columnAccessor) as Company[];
    setRecords(sortStatus.direction === 'desc' ? data.reverse() : data);
  }, [sortStatus]);

  return (
    <DataTable
      withTableBorder
      withColumnBorders
      records={records}
      columns={[
        { accessor: 'name', width: '40%', sortable: true },
        { accessor: 'streetAddress', width: '60%' },
        { accessor: 'city', width: 160, sortable: true },
        { accessor: 'state', textAlign: 'right', sortable: true },
      ]}
      sortStatus={sortStatus}
      onSortStatusChange={setSortStatus}
      sortIcons={{
        sorted: <IconChevronUp size={14} />,
        unsorted: <IconSelector size={14} />,
      }}
    />
  );
}
Name
Street address
City
State
Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburghCA
Cummerata - Kuhlman6389 Dicki StreamSouth GateNH
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburghKS
Feest, Bogan and Herzog21716 Ratke DriveStromanportWY
Goldner, Rohan and Lehner632 Broadway AvenueNorth LouieWY
Goyette Inc8873 Mertz RapidDorthysideID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Kling - McLaughlin8346 Kertzmann SquareSouth JoesphID
Rau - O'Hara7508 Lansdowne RoadShieldsboroughMI
Runte Inc2996 Ronny MountMcAllenMA
Shanahan, Robel and Beier378 Berta CrescentWest GerryKS
Tillman - Jacobi57918 Gwendolyn CirclesSheridanportMI
No records

Head over to the next example to discover more features.

Mantine DataTable is used and trusted by