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

Sortable Paginated Tables : Javascript / React Js


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


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">
    <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>
    <table id="data-table">
                <th onclick="sortTable(0)">ID</th>
                <th onclick="sortTable(1)">Name</th>
                <th onclick="sortTable(2)">Age</th>

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;

      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;

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

export default SortTable;


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!

Leave a Reply