How to Sort Data With React-Table Library

Irakli Tchigladze Feb 02, 2024
How to Sort Data With React-Table Library

Sometimes, React developers must create a table component to display large amounts of data in an organized way. This article will explain react-table, a great library with custom components to display data in a table.

Display and Sort Data as a Table Using the react-table Library

The simplest way to describe the react-table library is a set of hooks for building flexible yet multi-functional tables and grids for displaying your data.

The hooks don’t render any CSS or HTML elements, despite what you may think.

The developer behind the react-table library recently released a new and improved version 7. It is designed around hooks, which are effective but require some learning time.

the useTable Hook in React

This is the main hook of the library that accepts one argument, the options object, which you can use to supply the data that needs to be displayed, customize the functionality (such as default sorting or filters for the tables), and more.

The argument needs to contain two array values: columns and data.

To learn more about options, and the conditions for these two arrays, read the official documentation page.

Default Sorting With the react-table Library

Typically, your table should contain data upon initialization. react-table gives you the freedom to sort initial data.

After you’ve passed the two required arrays through the options object, you can pass the third initialState option, an object with key-value pairs that specify default formatting, filtering, and sorting for the initial data.

Let’s look at an example instance of the useTable() hook.

useTable(
    {
        columns,
        data,
        initialState: {
            sortBy: [
                {
                    id: 'id',
                    desc: true
                }
            ]
        }
    }

In this example, we use the sortBy array to specify that we want to sort the id column and sort it in descending order (alphabetically) by default.

If you wanted to sort by two columns simultaneously, you could add another object to specify the column or the order of the data.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn