How to Create a Sortable Table in React

Irakli Tchigladze Feb 02, 2024
How to Create a Sortable Table in React

Creating a table is one of the best ways to display large volumes of information on your website. Modern web applications usually store a lot of data that needs to be displayed on the screen.

Users expect some way to sort or filter the table to find what they’re looking for. Forcing them to look through thousands of rows is bad UX practice.

The simplest solution is to create a table where columns can be alphabetically sorted, so the users can find the information they need.

This article will explore how to create a sortable table in React.

Create a Sortable Table in React

First, we will discuss how to create a table in a web application and then show how to make it sortable.

Luckily, HTML has built-in elements for creating a very basic table. These elements are: <table>, <thead>, <tr>, <th>, <tbody>, and so on. If you’d like more information about creating tables in HTML, refer to this guide.

In this case, we already built a simple table. Let’s look at the code below:

<table className="m-table">
        <thead>
          <tr>
            <th onClick={(e) => onSort(e, "firstName")}>First Name</th>
            <th onClick={(e) => onSort(e, "lastName")}>Salary</th>
          </tr>
        </thead>
        <tbody>
          {data.map(function (person, index) {
            return (
              <tr key={index} data-item={person}>
                <td data-title="firstName">{person.firstName}</td>
                <td data-title="lastName">{person.lastName}</td>
              </tr>
            );
          })}
        </tbody>
  </table>

For simplicity, our component (and web application) will be this one table.

As you can see, we have two <th> elements, which stand for table headers. In other words, our table will have two column labels: the first will be the First Name, and the other will be the Salary.

Each of these elements has an onClick handler, which calls the onSort() event handler with two arguments - an event object and the property name associated with values from each column.

That’s all for our <thead> element.

Moving to the table body, we used the map() method to go over every record in the data array to create table row elements (<tr>) with table data elements (<td>). We set its key attribute to index, a standard way to avoid errors in React.

The map() method takes every item in the array, reads its properties firstName and lastName, and fills the table rows with this information. Note that these property names are also passed to the onSort() method when you click the headers.

Sort Table Rows in React

Now let’s look at the component’s business logic, which makes it possible to sort records of the table. The onSort() function handles sorting values in the table.

Let’s look at the function and the sample data stored in the data state variable.

  const [data, updateData] = useState([
    { firstName: "Irakli", lastName: "Tcigladze" },
    { firstName: "George", lastName: "Smith" },
    { firstName: "Mark", lastName: "Wayans" },
    { firstName: "Michael", lastName: "Simmons" },
    { firstName: "Dirk", lastName: "Johnson" },
    { firstName: "Casey", lastName: "Dawson" }
  ]);
  const onSort = (event, sortKey) => {
    const tempData = [...data];
    updateData(tempData.sort((a, b) => a[sortKey].localeCompare(b[sortKey])));
  };

Our available data is relatively standard. We have an array of objects that describe a person.

The onSort() function takes two arguments. These are the synthetic event objects and the key for sorting these values.

In other words, the object’s property where specific values are stored. For first name values in the table, the key is firstName because that’s the object property that holds the first names, and for last names, it’s lastName.

In React, state data should not be directly mutated, so we copy the items in the data array and store it in the tempData variable.

Next, we use the sort() function, which accepts a callback function argument that describes how to compare values in the data. In this case, we use the key argument (in other words, the property’s name) to access each object’s firstName or lastName values.

Then we use the localeCompare() method to determine which value should come first. Then, we arrange the data accordingly.

You can check out the sortable table in React on CodeSandbox. Try clicking one of the headers (column labels), and you’ll see that it alphabetically sorts 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

Related Article - React Table