Home » leet code » Sortable Paginated Tables : Javascript / React Js

Sortable Paginated Tables : Javascript / React Js

Introduction

Tables are a fundamental component of web development, often used to present data in a structured format. However, when dealing with large datasets, managing and navigating through the information can become challenging. This is where sorting and pagination come into play. In this blog post, we’ll explore how to implement sorting functionality on HTML tables using JavaScript, creating sortable and paginated tables for better data organization and user experience.


After Clicked on Age Label on table , it sort the column according to age in decreasing order

Prerequisites

Before diving into the implementation, it’s helpful to have a basic understanding of HTML, CSS, and JavaScript. Familiarity with DOM manipulation and event handling in JavaScript will be particularly beneficial. Additionally, ensure you have a text editor and a web browser installed to test your code.


Understanding Sortable and Paginated Tables

Sortable tables allow users to rearrange the rows based on specific criteria, such as alphabetical order, numerical value, or date. Pagination, on the other hand, involves dividing large datasets into manageable chunks or pages, enhancing readability and performance. By combining these functionalities, we can create user-friendly tables that facilitate efficient data exploration and analysis.


Implementing Sorting in HTML Tables

To implement sorting on an HTML table, we’ll utilize JavaScript to add event listeners to the table headers. When a header is clicked, we’ll dynamically sort the table rows based on the corresponding column’s values. Let’s illustrate this with an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sortable Table</title>
    <script src="script.js" defer></script>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th onclick="sortTable(0)">ID</th>
                <th onclick="sortTable(1)">Name</th>
                <th onclick="sortTable(2)">Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Nilesh</td>
                <td>25</td>
            </tr>
            <tr>
                <td>2</td>
                <td>SpeakLouder</td>
                <td>30</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Raut</td>
                <td>20</td>
            </tr>
 <tr>
                <td>4</td>
                <td>Dev</td>
                <td>43</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

In this example, each table header (<th>) has an onclick attribute calling a JavaScript function sortTable() with the column index as an argument. The sortTable() function will sort the rows based on the clicked column.


JavaScript Code for Sorting

Now, let’s implement the sortTable() function in our script.js file:

function sortTable(columnIndex) {
    let table, rows, switching, i, x, y, shouldSwitch;
    table = document.getElementById("data-table");
    switching = true;

    while (switching) {
      switching = false;
      rows = table.rows;

      for (i = 1; i < rows.length - 1; i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("td")[columnIndex];
        y = rows[i + 1].getElementsByTagName("td")[columnIndex];

        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      }

      if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
      }
    }
}

This JavaScript function performs a simple bubble sort algorithm to arrange the rows based on the values in the specified column.


Deafault Table

Image description

Clicked on the Colum Label age , it sort the colum according to age in decreasing order

Image description

Table Sorting using React js

import React, { useState } from 'react';

const SortTable = () => {
    const [data, setData] = useState([
        { id: 1, name: 'Nilesh', age: 25 },
        { id: 2, name: 'SpeakLouder', age: 30 },
        { id: 3, name: 'Raut', age: 20 },
         { id: 4, name: 'Devto', age: 21 }
    ]);
    const [sortBy, setSortBy] = useState('');
    const [sortOrder, setSortOrder] = useState('asc');

    const handleSort = (column) => {
        const order = column === sortBy && sortOrder === 'asc' ? 'desc' : 'asc';
        setData(prevData => {
            const sortedData = [...prevData].sort((a, b) => {
                if (a[column] < b[column]) return order === 'asc' ? -1 : 1;
                if (a[column] > b[column]) return order === 'asc' ? 1 : -1;
                return 0;
            });
            return sortedData;
        });
        setSortBy(column);
        setSortOrder(order);
    };

    return (
        <table>
            <thead>
                <tr>
                    <th onClick={() => handleSort('id')}>ID</th>
                    <th onClick={() => handleSort('name')}>Name</th>
                    <th onClick={() => handleSort('age')}>Age</th>
                </tr>
            </thead>
            <tbody>
                {data.map(item => (
                    <tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
};

export default SortTable;

Conclusion

In this blog post, we’ve learned how to apply sorting functionality to HTML tables using JavaScript, enabling users to interactively organize and explore data. By incorporating pagination techniques and responsive design principles, we can further enhance the usability and performance of our web applications. So go ahead, implement sortable and paginated tables to streamline data presentation and improve user experience!

For more advanced sorting algorithms and techniques, you can explore resources such as this article.


Remember, mastering the art of table manipulation opens up endless possibilities for creating dynamic and user-friendly web interfaces. Experiment with different features and customization options to tailor the tables to your specific needs and preferences. Happy coding!

1 thought on “Sortable Paginated Tables : Javascript / React Js”

Leave a Reply