Blog>
Snippets

Implementing Column Sorting with TanStack Table

Show code on using the `useSortBy` hook from TanStack Table to add sorting functionality to table columns.
import { useTable, useSortBy } from 'react-table';
Import necessary hooks from react-table.
const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data }, useSortBy);
Initialize the useTable hook along with useSortBy for sorting functionality.
return (
  <table {...getTableProps()}>
    <thead>
      {headerGroups.map(headerGroup => (
        <tr {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map(column => (
            <th
              {...column.getHeaderProps(column.getSortByToggleProps())}
            >
              {column.render('Header')}
              <span>
                {column.isSorted
                 ? column.isSortedDesc
                   ? ' 🔽'
                   : ' 🔼'
                 : ''}
              </span>
            </th>
          ))}
        </tr>
      ))}
    </thead>
    <tbody {...getTableBodyProps()}>
      {rows.map(row => {
        prepareRow(row);
        return (
          <tr {...row.getRowProps()}>
            {row.cells.map(cell => {
              return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
            })}
          </tr>
        );
      })}
    </tbody>
  </table>
);
Render the table, including sortable headers indicated by up/down arrows depending on the sort state.
};
Close the Table component.
export default Table;
Export the Table component for use in other parts of the application.