Everything you need as a full stack developer

React Tables with sorting and pagination

- Posted in React by

TL;DR The article discusses creating interactive tables in React using the react-table library. It covers implementing sorting with React hooks and pagination, allowing users to efficiently manage large datasets.

Mastering React Tables with Sorting and Pagination

As developers, we've all been there – staring at a sea of data, struggling to make sense of it all. That's where the mighty table comes in – a stalwart ally in our quest for organization and clarity. In this article, we'll delve into the world of React tables, exploring how to implement sorting and pagination with ease.

The Basics: Creating a Simple Table

Before we dive into the juicy stuff, let's start with the fundamentals. To create a basic table in React, you can use the table component from HTML. However, this is where things get interesting – we want our table to be interactive, so we'll need to bring in some additional libraries.

For this example, we'll use the popular react-table library, which provides an elegant solution for creating dynamic tables. First, let's install it using npm:

npm install react-table

Next, create a new React component and import the necessary dependencies:

import React from 'react';
import { Table } from 'react-table';

const data = [
  {
    name: 'John Doe',
    age: 25,
  },
  {
    name: 'Jane Doe',
    age: 30,
  },
];

function App() {
  return (
    <div>
      <Table data={data} columns={[
        {
          Header: 'Name',
          accessor: 'name',
        },
        {
          Header: 'Age',
          accessor: 'age',
        },
      ]} />
    </div>
  );
}

This will render a simple table with two columns – name and age. However, we're just getting started.

Sorting: The Power of React Hooks

Now that we have our basic table set up, let's add some sorting magic using the useState hook from React. We'll create a new state variable to store the current sort order:

import React, { useState } from 'react';
import { Table } from 'react-table';

const data = [
  // ...
];

function App() {
  const [sortOrder, setSortOrder] = useState({ field: 'name', direction: 'asc' });

  function handleSort(field) {
    if (field === sortOrder.field) {
      setSortOrder({ ...sortOrder, direction: sortOrder.direction === 'asc' ? 'desc' : 'asc' });
    } else {
      setSortOrder({ field, direction: 'asc' });
    }
  }

  return (
    <div>
      <Table data={data} columns={[
        // ...
      ]}
        sorted={[
          { id: 'name', desc: sortOrder.direction === 'desc' },
          { id: 'age', desc: false },
        ]}
        onSort={handleSort}
      />
    </div>
  );
}

In this example, we're using the onSort prop to pass a function that updates our sort order state. We're also defining two columns with sorting enabled – name and age.

Pagination: The Art of Page Management

Now that our table is sorted, it's time to tackle pagination. We'll use the useState hook again to store the current page number:

import React, { useState } from 'react';
import { Table } from 'react-table';

const data = [
  // ...
];

function App() {
  const [pageNumber, setPageNumber] = useState(1);

  function handlePageChange(page) {
    setPageNumber(page);
  }

  return (
    <div>
      <Table data={data} columns={[
        // ...
      ]}
        sorted={[
          { id: 'name', desc: sortOrder.direction === 'desc' },
          { id: 'age', desc: false },
        ]}
        onSort={handleSort}
        pagination={{
          page: pageNumber,
          pageCount: 5, // number of pages
          onPageChange: handlePageChange,
        }}
      />
    </div>
  );
}

In this example, we're using the pagination prop to pass an object with our current page number and a function to update it. We're also defining the total number of pages using the pageCount property.

Conclusion: Mastering React Tables

And that's it – we've successfully implemented sorting and pagination in our React table! With these techniques, you'll be able to create dynamic tables that adapt to your users' needs. Remember to keep your code organized, and don't hesitate to reach out for help when needed.

As always, the code is available on GitHub, so feel free to clone it and start experimenting. Happy coding!

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more