• Articles
  • Tutorials
  • Interview Questions

React Table - Create Table in ReactJS

React Table - Create Table in ReactJS

Table of content

Show More

React Table offers diversified benefits, such as providing a simple and flexible API for creating tables, supporting server-side data fetching, and offering built-in features like sorting, filtering, and pagination. In this blog, we will dive into the world of React Table and explore how to create tables with practical examples. Whether you’re a beginner or an experienced developer, this guide will equip you with the knowledge and skills to leverage React Table and create stunning tables that captivate your users.

Watch our React JS course video for practical tips to learn React:

Video Thumbnail

Understanding the React Table

React Table is a powerful and flexible library for creating tables in React applications. It provides a declarative and efficient way to render and manipulate tabular data, making it easier to handle complex table functionalities such as sorting, filtering, pagination, and more. React Table abstracts away many of the low-level complexities of working with tables, allowing developers to focus on building intuitive and interactive table components.

React Table follows a modular architecture, providing separate components for different table elements and functionalities. This modular approach allows for better reusability and maintainability of table components.

Know everything about React through our React JS Course.

How to Create a React Table with Examples?

How to Create a React Table?

The essential steps involved in creating a React table include setting up the React environment, installing necessary dependencies, defining the table structure, populating data, and handling interactions. By following these steps, you will be equipped with the knowledge and skills to create dynamic and interactive tables that effectively present your data.

Get 100% Hike!

Master Most in Demand Skills Now!

Setting Up React Table

Prior to creating a React table, it is significant to have a basic React environment established. This can be accomplished by utilizing tools such as Create React App (CRA) or manually setting up a React project. Once the environment has been established, proceed to the project directory and follow the steps outlined below.

To integrate React Table into your project, it is necessary to install the essential dependencies and import the relevant components. React Table is dependent on two primary dependencies, including react-table as well as react-table-styles.

Installing Dependencies

You can install these dependencies using npm or yarn:

npm install react-table react-table-styles

Or

yarn add react-table react-table-styles

Once the dependencies are installed, you can import the necessary components into your code:

import React from 'react'; import { useTable } from 'react-table'; import 'react-table-styles';

With the dependencies imported, you are ready to start building your table components using React Table.

Basic Table Structure and Data

To create a basic table structure using React Table, you need to define the table columns and data. React Table provides the useTable hook to define and configure the table.

We will create a new file, Table.js, and import the necessary dependencies:

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

In this example, we import the useTable function from react-table for creating the table.

Now, let’s define the Table component and its JSX structure:

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({
    columns,
    data,
  });
  return (
    <table {...getTableProps()}>
      <head>
        {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>
  );
};
export default Table;

In this code, we define a functional component called Table. It receives columns and data as props. We then use the useTable hook provided by react-table to extract the necessary table-related methods and data.

The getTableProps, getTableBodyProps, headerGroups, rows, and prepareRow variables are destructured from the useTable hook. These are essential for setting up the table structure and rendering the table rows and columns.

Inside the JSX, we use .map() functions to iterate over the headerGroups and rows arrays and render the table headers and cells dynamically. The column.render(‘Header’) and cell.render(‘Cell’) functions render the header and cell content, respectively.

Go through these Android Interview Questions to excel in your interview.

Populating Data

To display data in the table, it is pertinent to provide the Table component with the columns and data props. Moreover, to establish this, we can create a new file called App.js and define sample data and columns within it:

import React from 'react';
import Table from './Table';
const App = () => {
  const data = React.useMemo(
    () => [
      { id: 1, name: 'John Doe', age: 28 },
      { id: 2, name: 'Jane Smith', age: 32 },
      // Additional data rows...
    ]
    []
  );
  const columns = React.useMemo(
    () => [
      { Header: 'ID', accessor: 'id' },
      { Header: 'Name', accessor: 'name' },
      { Header: 'Age', accessor: 'age' },
    ],
    []
  );
  return (
    <div>
      <h1>React Table Example</h1>
      <Table columns={columns} data={data} />
    </div>
  );
};
export default App;

In this example, we define the data and column variables using the React.useMemo hook. The data array contains the actual data rows, while the columns array defines the table columns with their respective headers and accessors.

Finally, we render the Table component, passing the columns and data props.

Want to organize your data more properly using charts? Why don’t you go through React Charts blog to select the one which fits you.

Styling and Interactions

To make the table visually appealing and add interactive features, you can apply custom styles and handle user interactions. Here’s an example of adding some basic styles to the table:

// Inside Table.js
import './Table.css';
// Inside Table component JSX
<table className="custom-table" {...getTableProps()}>
  {/* Rest of the JSX */}
</table>

Create a new file, Table.css, in the same directory and define the custom styles:

.custom-table {
  width: 100%;
  border-collapse: collapse;
}
.custom-table the,
.custom-table td {
  padding: 8px;
  border: 1px solid #ddd;
}

In this example, we define a class called custom-table and apply it to the table component. The provided styles set the table width to 100% and define padding and borders for table headers and cells.

Feel free to customize the styles according to your requirements.

Work on your React JS basics through our React JS Tutorial.

Conclusion

By following these steps, you can create a basic React table using the react-table package. Starting with setting up the environment, installing dependencies, and defining the table structure, you can populate data dynamically and customize the table’s appearance and behavior. Creating a React table allows you to present tabular data in a structured and visually appealing manner, enhancing the user experience of your React applications.

Course Schedule

Name Date Details
Web Development Courses 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full-Stack-Development.jpg