1. Home
ReactJS

ReactJS Tutorial: A Comprehensive Guide

Master ReactJS with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and build dynamic web applications effortlessly.

  • 10
  • 3
right-top-arrow
5

React Table: From Basics to Advanced Functionality

Updated on 03/09/2024429 Views

As a web developer passionate about user experience (UX), I've always found data presentation crucial. React, a framework for building dynamic and interactive web applications excels at this. 

However, efficient rendering and manipulation of tabular datasets require a specialized solution. Enter datatable in React JS, a reusable UI component designed to streamline this process within React projects.

Throughout my experience using React tables, I've discovered many benefits. React tables effortlessly presenting complex datasets in a clear and organized manner. React tables achieve that through features like sorting, filtering, and pagination. Furthermore, they promote code reusability and maintainability, saving me valuable time and effort in the long run.

Getting Started with React Table

Before we get into the specifics, let's establish a common ground. I'm assuming you possess a basic understanding of React concepts like React data table components, props, and state management. Additionally, familiarity with JavaScript fundamentals will be advantageous in grasping the React table example we'll encounter throughout this exploration.

Setting Up React Table in Your Project

The first step towards incorporating React tables into your project involves installation. We'll utilize npm (Node Package Manager) for this purpose. To access your project directory, open your terminal and navigate there. Then, execute the following command to install the react-table library:

Bash

npm install react-table

This command fetches the necessary files from the npm registry and installs them within your project's node_modules folder. Once the installation is complete, you can use React tables in your React components.

Configuring Data Sources

React tables are versatile in terms of data sources. I've utilized various data structures to populate my tables, including:

Data Source

Description

Arrays of Objects

This is a common approach. Each object in the array represents a single row of data in the table, and its properties correspond to the table's columns.

External Data Sources

React tables can fetch data from external APIs or databases seamlessly. In a later section, we'll explore data-fetching techniques.

Here's a React table example of an array of objects that we'll use throughout this guide to demonstrate various tables in React functionalities:

JavaScript Code

const data = [

  { id: 1, name: 'John Doe', age: 30, city: 'New York' },

  { id: 2, name: 'Jane Smith', age: 25, city: 'Los Angeles' },

  { id: 3, name: 'Michael Brown', age: 40, city: 'Chicago' },

];

Basic Table Rendering

Now that our data source is prepared, let's create a simple React data table component to render a basic table using react-table. Here's the code:

JavaScript Code

import React from 'react';

import { useTable } from 'react-table';

function BasicTable() {

  const columns = [

    { Header: 'ID', accessor: 'id' },

    { Header: 'Name', accessor: 'name' },

    { Header: 'Age', accessor: 'age' },

    { Header: 'City', accessor: 'city' },

  ];

  const data = [

    { id: 1, name: 'John Doe', age: 30, city: 'New York' },

    { id: 2, name: 'Jane Smith', age: 25, city: 'Los Angeles' },

    { id: 3, name: 'Michael Brown', age: 40, city: 'Chicago' },

  ];

  const { getTableProps, 

          headerGroups, 

          rows, 

          prepareRow } = useTable({ columns, data });

  return (

    <table {...getTableProps()}>

      <thead>

        {headerGroups.map((headerGroup) => (

          <tr key={headerGroup.id}>

            {headerGroup.headers.map((column) => (

              <th key={column.id}>{column.Header}</th>

Customizing React Data Table Components 

We have established the foundation for using Datatable in React JS. Now, let's delve deeper and customize the visual appearance and behavior of our React data table components.

Styling and Theming

The default styling of React tables might not always match your project's design. Fortunately, React tables offer a high degree of customization through CSS classes. These classes can be applied directly to the table in React elements or incorporated into a global stylesheet.

Here's a React table example of how to style the table header cells using CSS classes:

CSS Code

.rt-tr > th {

  background-color: #f2f2f2;

  padding: 10px;

  border: 1px solid #ddd;

  text-align: left;

}

This code snippet targets all th elements within table rows (rt-tr) and applies styles for background color, padding, border, and text alignment. You can achieve various visual customizations for your React table by leveraging CSS selectors and properties.

Adding Custom Headers and Footers

React tables allow you to create custom headers and footers that extend beyond the basic functionality provided by default. This lets you incorporate additional information, search bars, or pagination controls. To implement a custom header, you can utilize the renderHeader prop provided by the useTable hook. 

Here's a basic React table example of a custom header that displays a search bar:

JavaScript

function MyCustomHeader({ header }) {

  return (

    <div>

      {header.Header}

      <input type="text" placeholder="Search..." />

    </div>

  );

}

const MyTable = () => {

  // ... table definition

  const { getTableProps, headerGroups, rows, prepareRow } = useTable({

    columns,

    data,

    headerComponent: MyCustomHeader,

  });

  // ... table rendering

};

In this react table example, the MyCustomHeader component renders the original header text alongside a search input field. Similarly, you can create custom footers using the renderFooter prop from useTable.

Implementing Row and Column Styling

In addition to styling the overall table in react structure, you can apply styles to individual rows and columns. React tables provide mechanisms for achieving this level of granular control. To style rows, you can use the className prop provided by the prepareRow function from useTable

For a react table example, highlight rows that meet certain criteria. Here's how you could achieve this:

JavaScript

const MyTable = () => {

  // ... table definition

  const { getTableProps, headerGroups, rows, prepareRow } = useTable({

    columns,

    data,

  });

  const prepareMyRow = (row) => {

    prepareRow(row);

    return { ...row, className: row.original.age > 30 ? 'highlight-row' : '' };

  };

  // ... table rendering

};

In this example, the prepareMyRow function checks the age property of each row's data. If the age exceeds 30, it assigns a CSS class named highlight-row to the row, which you can define in your stylesheet to achieve the desired visual effect.

Similarly, you can style individual columns using the accessor property within the column definition object. This allows you to target specific columns with CSS selectors.

Advanced Features of React Table 

Having established a solid foundation for customizing datatables in React JS, let's delve into their more advanced functionalities. These features empower you to create highly interactive and user-friendly data exploration experiences within your React applications.

Pagination and Infinite Scrolling

Large datasets can overwhelm users if presented in their entirety on a single page. React tables offer built-in support for pagination, allowing users to navigate through the data in manageable chunks. The useTable hook provides functionalities for defining the page size and implementing controls for navigating between pages. 

Here's a simplified example demonstrating basic pagination:

JavaScript

const MyTable = () => {

  const [pageIndex, setPageIndex] = useState(0); // Track current page

  const {

    getTableProps,

    headerGroups,

    rows,

    prepareRow,

    page, // Access pagination information

    canPreviousPage,

    canNextPage,

    pageOptions,

    gotoPage,

    pageCount,

    pageSize,

    setPageSize,

  } = useTable({

    columns,

    data,

    initialState: { pageIndex: pageIndex }, // Set initial page

  });

  const handleNextPage = () => gotoPage(page + 1);

  const handlePreviousPage = () => gotoPage(page - 1);

  const handlePageSizeChange = (e) => setPageSize(Number(e.target.value));

  // ... table rendering

  return (

    <div>

      <table {...getTableProps()}>

        {/* ... table structure */}

      </table>

      <div>

        <button onClick={handlePreviousPage} disabled={!canPreviousPage}>

          Previous Page

        </button>

        <span>

          Page {page + 1} of {pageCount}

        </span>

        <button onClick={handleNextPage} disabled={!canNextPage}>

          Next Page

        </button>

        <select value={pageSize} onChange={handlePageSizeChange}>

          {pageOptions.map((option) => (

            <option key={option.value} value={option.value}>

              Show {option.value} rows

            </option>

          ))}

        </select>

      </div>

    </div>

  );

};

This example utilizes the useTable hook with additional properties like page, canPreviousPage, canNextPage, and pagination control functions. It also demonstrates options for changing the page size dynamically.

Filtering and Sorting Data

The ability to filter and sort data is crucial for efficient data exploration. React tables provide comprehensive functionalities for both functionalities. Filtering allows users to narrow down the displayed data based on specific criteria. You can implement filtering using the useFilters hook from react-table

Here's a basic example demonstrating filtering on a single column:

JavaScript

const MyTable = () => {

  const filters = useFilters([

    {

      id: 'age',

      value: null, // Initial filter value

      preFilteredRows: (rows) =>

        rows.filter((row) => row.original.age > 25), // Example filter function

    },

  ]);

  const { getTableProps, headerGroups, rows, prepareRow,setFilter } = useTable(

    {

      columns,

      data,

      filterTypes: {

        // Define custom filter types if needed

      },

      autoFilters: true, // Enable automatic updates based on filter changes

    },

    filters

  );

  const handleFilterChange = (e) => {

    setFilter('age', e.target.value); // Update filter based on user input

  };

  // ... table rendering

  return (

    <div>

      <input type="number" onChange={handleFilterChange} placeholder="Filter by Age" />

      <table {...getTableProps()}>

        {/* ... table structure */}

      </table>

    </div>

  );

};

This example utilizes the useFilters hook and defines a filter for the age column. It also demonstrates applying an initial filter and updating it based on user input.

Integrating React Table with External Libraries and Best Practices 

Now, let's delve into integrating React tables with external libraries and discuss best practices for using them effectively in your projects.

Incorporating Redux for State Management

As your React applications grow in complexity, managing the application state becomes increasingly essential. Redux, a popular state management library, can be valuable in such scenarios. You can integrate React tables with Redux to centrally manage the table state.

Here's a simplified overview of the approach:

  1. Define Redux actions for modifying the table state (e.g., sorting, filtering, pagination changes).
  2. Create a Redux reducer to handle these actions and update the table state accordingly.
  3. Connect your react data table components to the Redux store to access and update the table state.

Utilizing React Query for Server Data Fetching

While React tables can handle various data sources, including local arrays, fetching data from servers is often the case for real-world applications. A well-liked library for controlling asynchronous data fetching in React apps is called React Query. You can integrate React Query with React tables to streamline data fetching and error handling.

Here's a simplified breakdown of the process:

  1. Use React Query to define a query function that fetches data from your server.
  2. Pass the query function as a prop to the useTable hook.
  3. React Query will automatically handle data fetching, updates, and error states, reflecting them in your React data table component.

Enhancing Performance with Memoization Techniques

React tables can become computationally expensive, especially when dealing with large datasets. To optimize performance, you can leverage memorization techniques. Memoization involves caching the results of expensive computations and reusing them when the same arguments are provided.

Here are some ways to apply memoization with React tables:

  • Utilize React's built-in React.memo function to prevent unnecessary re-renders of custom components used within your table cells.
  • If your table cells involve calculations based on the original data, consider memoizing these calculations using libraries like reselect to avoid redundant computations.

Conclusion

This thorough guide has provided you with the information and skills necessary to exploit the potential of datatable in React JS in your React projects. From setting them up and customizing their appearance to utilizing advanced features like pagination, filtering, and integration with external libraries, you have a solid foundation for crafting exceptional data display experiences. Remember, effective communication and collaboration are crucial aspects of web development. Feel free to share what you know, ask questions, and add to the ongoing discussion on React tables!

FAQs

  1. Why do we use React tables?

As a web developer, I use React tables to present and manipulate tabular data efficiently within React applications. They offer features like sorting, filtering, and pagination, improving user experience for data exploration.

  1. What are the data types in the React table?

React tables are versatile and can handle various data structures, including arrays of objects and data fetched from external APIs or databases.

  1. How do you use React tables?

You'll install the react-table library to use React tables and define your data and columns. The library's useTable hook provides functionalities for rendering and interacting with the table.

  1. How do I improve my React table performance?

Consider virtual rendering techniques and memoization of expensive computations within your table cells for large datasets to optimize performance.

  1. What is the best React table?

While there are other options, React Table (from TanStack) is a popular and well-maintained open-source library offering comprehensive features for building React data tables.

  1. How do you filter a table in React?

React tables provide functionalities for filtering data based on specific criteria. You can define filters for each column and implement mechanisms for applying and clearing filters.

  1. Is React Table open source?

React Table is an open-source library that allows you to use and contribute to its development freely.

  1. How do I edit a row in the React table?

While basic React tables don't offer built-in editing functionality, you can achieve this by integrating third-party libraries or custom components that handle row editing logic.

  1. What is the date format in the React table?

React tables themselves don't enforce a specific date format. You can format date data according to your needs using JavaScript libraries like Moment.js or custom formatting functions.

Ankit Mittal

Ankit Mittal

Working as an Senior Software Engineer at upGrad, with proven experience across various industries.

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...