Categories
JavaScript React

Reactjs Table Component – React Table

Spread the love

React Table is a simple table component that we can use to create tables in React.

It comes with a good hooks API to make using it easy in function components.

We can start using it by install it:

npm install react-table

Once we did that, we can use it as follows:

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

const data = [
  { id: 1, firstName: "jane", lastName: "doe" },
  { id: 2, firstName: "joe", lastName: "smith" },
  { id: 3, firstName: "may", lastName: "jones" }
];

const columns = [
  {
    Header: "first name",
    accessor: "firstName"
  },
  {
    Header: "last name",
    accessor: "lastName"
  }
];

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

  return (
    <div>
      <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 => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

We use the useTable hook, which takes an object with columns and data arrays which are in the format that we have on the top of the file.

The hook returns the getTableProps, getTableBodyProps, headerGroups, rows, prepareRow which we use in our table.

We just call and use them in the places that we have above to that we can get the rows and headings displayed.

row.cells have the row entries.

getTableBodyProps return the props for the tbody element.

headerGroups have the header data which we can use to create the table headers from the columns array.

Then we’ll see that we have a table with first name and last name columns with the corresponding names displayed.

Now we create a table without going through the effort of writing out all the code ourselves.

Leave a Reply

Your email address will not be published. Required fields are marked *