vue.js logo

Creating React Table npm


Step 1: Install `react-table`

First, install the react-table package via npm or yarn:


npm install react-table

or

yarn add react-table


Step 2: Basic Setup

Here's a basic example to get you started with `react-table`:


App.js


                import React, { useMemo } from 'react';
import { useTable } from 'react-table';
import './App.css';

const App = () => {
  const data = useMemo(
    () => [
      {
        col1: 'Hello',
        col2: 'World',
      },
      {
        col1: 'react-table',
        col2: 'rocks',
      },
      {
        col1: 'whatever',
        col2: 'you want',
      },
    ],
    []
  );

  const columns = useMemo(
    () => [
      {
        Header: 'Column 1',
        accessor: 'col1', // accessor is the "key" in the data
      },
      {
        Header: 'Column 2',
        accessor: 'col2',
      },
    ],
    []
  );

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data });

  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>
  );
};

export default App;

App.css


          <style>
table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 10px;
  border: 1px solid #ddd;
  text-align: left;
}

thead {
  background-color: #f4f4f4;
}
</style>

Step 3: Explanation


Data and Columns: Define your table data and column definitions using the `useMemo` hook. This ensures that the data and columns are memoized and do not cause unnecessary re-renders.


useTable Hook: Destructure the necessary properties and methods from the useTable hook provided by `react-table`.


Rendering the Table: Use the `getTableProps`, `GetTableBodyProps`, `headerGroups`, `rows`, and `prepareRow` methods to render the table's structure.


Step 4: Advanced Features


`react-table` supports various advanced features, such as sorting, filtering, pagination, and more. To incorporate these features, you can extend the basic setup.


Example of Adding Sorting

To add sorting to your table, use the `useSortBy` plugin hook:


          import React, { useMemo } from 'react';
    import { useTable, useSortBy } from 'react-table';
    import './App.css';

    const App = () => {
      const data = useMemo(
        () => [
          {
            col1: 'Hello',
            col2: 'World',
          },
          {
            col1: 'react-table',
            col2: 'rocks',
          },
          {
            col1: 'whatever',
            col2: 'you want',
          },
        ],
        []
      );

      const columns = useMemo(
        () => [
          {
            Header: 'Column 1',
            accessor: 'col1',
          },
          {
            Header: 'Column 2',
            accessor: 'col2',
          },
        ],
        []
      );

      const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
      } = useTable({ columns, data }, useSortBy);

      return (
        <table {...getTableProps()}>
          <thead>
            {headerGroups.map(headerGroup => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map(column => (
                  <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                    {column.render('Header')}
                    <span>
                      {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
                    </span>
                  </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 App;

In this example, the useSortBy hook is added to enable sorting functionality.

Here’s a more advanced example of a plugin that wraps an HTTP client like Axios.