Site icon DataFlair

React Table

react tables

Job-ready Online Courses: Knowledge Awaits – Click to Access!

React Table is a powerful library that allows developers to create customizable and efficient tables in their React applications. It offers a variety of features that make it easier to manage and display large amounts of data in a tabular format.

In this article, we will explore the features of React Table, how to install it, and how to use it in a React application.

Installing React Table

Before we dive into using React Table, we need to install it. To install React Table, we can use the following command in the terminal:

npm install react-table

This will install the latest version of React Table and its dependencies in our project.

Basic Usage

Let’s start with a basic example of using React Table. We will create a table with three columns: Name, Age, and Email. Here is the code:

import React from "https://cdn.skypack.dev/react@17.0.1";
import ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";
import { useTable } from "https://cdn.skypack.dev/react-table@7.8.0";

function Table({ columns, data }) {
  const tableInstance = useTable({ columns, data });

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function App() {
  const columns = [
    {
      Header: 'Name',
      accessor: 'name',
    },
    {
      Header: 'Age',
      accessor: 'age',
    },
    {
      Header: 'Email',
      accessor: 'email',
    },
  ];

  const data = [
    {
      name: 'Mehul Garg',
      age: 22,
      email: 'mehulgarg@example.com',
    },
    {
      name: 'DataFlair',
      age: 18,
      email: 'dataflair@example.com',
    },
  ];

  return <Table columns={columns} data={data} />;
}

ReactDOM.render(<App />, document.getElementById('root'));

Output:

In this example, we import the useTable hook from React Table and create a Table component. We then use the useTable hook to create an instance of the table with the given columns and data.

Then we destructure some important values from the table instance, including getTableProps, getTableBodyProps, headerGroups, rows, and prepareRow. We use these values to render the table header and body.

In the getTableProps method, we pass any additional props we want to apply to the table element, such as className or style.

In the headerGroups.map method, we iterate over each header group and render a table row element. We also iterate over each header in the group and render a table header element for each column.

In the rows.map method, we iterate over each row and use the prepareRow method to prepare the row for rendering. We then render a table row element and iterate over each cell in the row, rendering a table data element for each cell.

The getCellProps and render methods are used to apply any additional props to the table data element.

With this basic example, we can see how easy it is to create a table with React Table. However, React Table has many more features that can make table management even easier and more efficient.

Advanced Features of React Table

React Table offers a variety of advanced features that can be used to create more complex and efficient tables. Let’s take a look at some of these features.

Sorting

Sorting is a common feature in tables that allows users to sort the data by a particular column. React Table makes sorting easy by providing a useSortBy hook that can be used to add sorting functionality to a table.

To use sorting in React Table, we need to add the useSortBy hook to the useTable hook, like this:

const tableInstance = useTable({ columns, data }, useSortBy);

We also need to update the table header to include a sorting icon.

<th {...column.getHeaderProps(column.getSortByToggleProps())}>
  {column.render('Header')}
  {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
</th>

Output:

In this example, we use the getSortByToggleProps method to get the props needed to toggle the sorting. We also render a sorting icon based on whether the column is currently sorted and whether it is sorted in descending order.

Pagination

Pagination is another common feature in tables that allows users to view the data in smaller, more manageable chunks. React Table provides a usePagination hook that can be used to add pagination functionality to a table.

To use pagination in React Table, we need to add the usePagination hook to the useTable hook, like this:

const tableInstance = useTable({ columns, data }, useSortBy, usePagination);

We also need to update the table body to only render a subset of the rows based on the current page and page size:

<tbody {...getTableBodyProps()}>
  {page.map((row) => {
    prepareRow(row);
    return (
      <tr {...row.getRowProps()}>
        {row.cells.map((cell) => (
          <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
        ))}
      </tr>
    );
  })}
</tbody>

Output:

Here we use the page property from the table instance to only render a subset of the rows.

When to use Table in React:

1. Large datasets:

React Table is optimized for handling large datasets efficiently. If you have a lot of data to display in a table, React Table can help you improve the performance of your application by only rendering the rows that are currently visible on the screen.

2. Complex table functionality:

If you need to implement advanced table functionality like sorting, filtering, grouping, or aggregation, React Table provides a comprehensive set of features to make it easy to implement.

When not to use Tables in React:

1. Simple tables:

If you only need to display a small amount of data in a basic table with no advanced functionality, you may not need to use React Table. In this case, you could use regular HTML and CSS to create your table.

2. Tight project timelines:

If you are working on a project with tight timelines and you do not have much time to learn a new library, you may not want to use React Table. In this case, you could consider using a simpler library or building your own table component from scratch.

Tanstack Table in React

Tanstack Table is a powerful and flexible table library for React applications that provides a simple and intuitive way to create, customize, and interact with tables. It is based on the popular React Table library, but with several key improvements that make it even more effective and user-friendly.

Features of Tanstack Table

It allows developers to easily customize the look and feel of their tables using CSS, or to create custom cell renderers and column filters to meet specific needs. It is designed to be highly optimized, with features like virtualization and memoization.

Tanstack Table also provides a range of advanced features and functionality.

For example, it supports nested tables, allowing us to create complex table structures.

const data = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  { id: 3, name: 'Bob', age: 40 },
  { id: 4, name: 'Sarah', age: 35 },
];

const columns = [
  { Header: 'ID', accessor: 'id' },
  { Header: 'Name', accessor: 'name' },
  { Header: 'Age', accessor: 'age' },
];

const tableInstance = TanStackTable.useTable({
  columns,
  data,
});

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
  tableInstance;

ReactDOM.render(
  <table {...getTableProps()}>
    <thead>
      {headerGroups.map((headerGroup) => (
        <tr {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map((column) => (
            <th {...column.getHeaderProps()}>{column.render('Header')}</th>
          ))}
        </tr>
      ))}
    </thead>
    <tbody {...getTableBodyProps()}>
      {rows.map((row) => {
        prepareRow(row);
        return (
          <tr {...row.getRowProps()}>
            {row.cells.map((cell) => (
              <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
            ))}
          </tr>
        );
      })}
    </tbody>
  </table>,
  document.getElementById('table')
);

Output

Conclusion:

React Table is a powerful library that provides a flexible and efficient way to create tables in React applications. With its rich set of features and hooks, React Table makes it easy to add sorting, pagination, filtering, grouping, and more.

React Table is highly customizable, and its API is designed to be easy to use and understand. Whether you’re building a simple table or a complex data visualization, React Table provides the tools you need to get the job done.

Exit mobile version