Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to sort the table in ascending order in ReactJS

Introduction

Sorting is a common task that we perform in our daily lives. It's just like organizing books in a library, arranging them alphabetically so that you can find them easily. In programming, and more specifically in ReactJS, we often need to sort tables for better user experience. In this blog post, we will learn how to sort a table in ascending order in ReactJS.

In programming, a table is nothing but an array of objects where each object represents a row in the table. And sorting a table means arranging the objects (rows) in a certain order.

Understanding ReactJS

Before diving into sorting tables, let's first understand what ReactJS is. ReactJS, often simply called React, is a JavaScript library for building user interfaces or UI components. It's like a box of Legos, each Lego block is a component, and you can combine them in various ways to create beautiful and interactive UIs.

Setting Up The Table

Let's start by setting up a simple table in React. We'll create a table with data about books - title, author, and year of publication.

import React from 'react';

const App = () => {
  const books = [
    { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },
    { title: '1984', author: 'George Orwell', year: 1949 },
    { title: 'One Hundred Years of Solitude', author: 'Gabriel Garcia Marquez', year: 1967 },
    // More books...
  ];

  return (
    <table>
      <thead>
        <tr>
          <th>Title</th>
          <th>Author</th>
          <th>Year</th>
        </tr>
      </thead>
      <tbody>
        {books.map((book, index) => (
          <tr key={index}>
            <td>{book.title}</td>
            <td>{book.author}</td>
            <td>{book.year}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default App;

This code will create a table that displays the title, author, and year of each book in our books array. The map function is used here to create a new array of <tr> elements for each book. It's like a factory conveyor belt, where each book is passed through and transformed into a <tr> element.

Sorting the Table

Now that we have our table, let's sort it in ascending order based on the title. We'll use the sort function provided by JavaScript to do this. This function takes a comparator - a function that determines the order of elements. It's like a referee in a game, deciding who wins based on a set of rules.

const App = () => {
  const books = [
    // Our book array
  ];

  // We'll sort the books in ascending order of their title
  const sortedBooks = books.sort((a, b) => a.title.localeCompare(b.title));

  return (
    // Our table code
  );
};

The localeCompare function is a string method that returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. It's like asking, "For these two books, which one should come first in the library?"

Making the Sorting Dynamic

The above code will always sort the table in ascending order based on the title. But what if we want to sort by different columns, like author or year? And what if we want to switch between ascending and descending order?

Let's add that functionality. We'll add a state variable sortConfig to keep track of the sorting configuration. We'll also add a function requestSort that updates this configuration.

import React, { useState } from 'react';

const App = () => {
  const books = [
    // Our book array
  ];

  const [sortConfig, setSortConfig] = useState({ key: 'title', direction: 'ascending' });

  const requestSort = (key) => {
    let direction = 'ascending';
    if (sortConfig.key === key && sortConfig.direction === 'ascending') {
      direction = 'descending';
    }
    setSortConfig({ key, direction });
  };

  // More code...
};

In the requestSort function, we check if the requested key is the same as the current sort key. If they are the same and the current direction is 'ascending', we switch to 'descending'. Otherwise, we set the direction to 'ascending'.

Now, let's use sortConfig to sort our books.

const App = () => {
  // Rest of the code...

  let sortedBooks = [...books];
  if (sortConfig !== null) {
    sortedBooks.sort((a, b) => {
      if (a[sortConfig.key] < b[sortConfig.key]) {
        return sortConfig.direction === 'ascending' ? -1 : 1;
      }
      if (a[sortConfig.key] > b[sortConfig.key]) {
        return sortConfig.direction === 'ascending' ? 1 : -1;
      }
      return 0;
    });
  }

  // Rest of the code...
};

Here, we first create a copy of books using the spread operator (...). This is because the sort function sorts the array in-place, meaning it modifies the original array. We don't want that. Then, we sort sortedBooks based on the sortConfig.

Finally, let's add a way for the user to trigger the sorting by clicking on the table headers.

const App = () => {
  // Rest of the code...

  return (
    <table>
      <thead>
        <tr>
          <th onClick={() => requestSort('title')}>Title</th>
          <th onClick={() => requestSort('author')}>Author</th>
          <th onClick={() => requestSort('year')}>Year</th>
        </tr>
      </thead>
      <tbody>
        {sortedBooks.map((book, index) => (
          // Rest of the code...
        ))}
      </tbody>
    </table>
  );
};

And there we have it! We can now sort our table in ascending or descending order based on the column we click.

Conclusion

Sorting tables is a common requirement in web applications. In this tutorial, we have learned how to sort a table in ascending order in ReactJS. We have also learned how to make the sorting dynamic, allowing the user to sort by different columns and switch between ascending and descending order.

Remember, understanding the concepts is more important than memorizing the code. The code is just a tool to implement the concepts.

Happy coding!