Getting Started With React Table With Fakestore API

Getting Started With React Table With Fakestore API

Written by krissanawat101 on Feb 10th, 2021 Views Report Post

Tables are an essential component in web development. They help to display the data in a clean and structured manner making it easy to understand and filter. It provides a clean and intuitive look to the overall UI and presents the information in concise and precise dimensions. It optimizes the overall user experience in terms of content on the website.

In this tutorial, we are going to learn how to use react table with remote data. We are going to fetch the data to be shown on the table from FakeStore API. The react-table libraries facilitate hooks for building fast and extendable tables and data grids for React. The component library also offers Sorting (Multi and Stable), Filters, Pivoting & Aggregation, Row Selection, Row Expansion, Column Ordering, Animatable, Virtualizability, and Resizability out of the box. Overall, a very dynamic and powerful table package that is highly customizable and lightweight as well.

Installing react table

For this tutorial, we are going to make implementations on codesandbox. Hence, we need to add the dependency for the react-table as shown in the screenshot below:

Untitled (2).png

Table component

Then, we need to create a folder called ./component inside which we need to create a file called Table.js which is going to hold the code for the table in React project:

Untitled (1).png

In Table.js, we need to import necessary packages as shown in the code snippet below:

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

Next, we need to create a function that takes in columns and table data as parameters from the parent component. Then, we need to create a new React table instance object by using the useTable hook as shown in the code snippet below:

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

Next, we need to construct table a structure. We can just grab the code example from the main documentation of the react-table package for this implementation. The code template for the table UI is provided in the code snippet below:

return (
    <table
      {...getTableProps()}
      className="table table-bordered table-condensed table-responsive"
      style={{ display: "table" }}
    >
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

Here, we have used the table element wrapping thead and tbody along with required rows and columns.

Working on main component

Now, we need to go to our main component which is App.js, and import the Table component as shown in the code snippet below:

import React, { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "./styles.css";
import Table from "./components/Table";

Here, we have also imported the other required dependencies for styling purpose.

Fetching data from Fakestore API

As mentioned before, we are going to fetch the data from the Fakestore API and display it in our React table. Now, in order to store the fetched data, we need to initialize the states using the useState hook. Then, we need to use the fetch method which takes in the API endpoint and returns the promise as JSON data inside the useEffect hook. Hence, every time the webpage loads, the data is fetched from the Fakestore API and stored in the products state as shown in the code snippet below:

export default function App() {
  const [products, setProducts] = useState([]);
  useEffect(() => {
    fetch("https://fakestoreapi.com/products")
      .then((res) => res.json())
      .then((json) => setProducts(json));
  }, []);

Before sending data to the Table component, we need to construct the columns data with proper table configuration options using the useMemo hook as shown in the code snippet below:

const columns = React.useMemo(
    () => [
      {
        Header: "Product Image",
        Cell: ({ row }) => {
          return (
            <img
              class="img-fluid img-rounded"
              width={200}
              src={row.original.image}
            />
          );
        }
      },
      {
        Header: "Product Title",
        accessor: "title" // accessor is the "key" in the data
      },
      {
        Header: "Product Price",
        accessor: "price"
      },
      {
        Header: "Product Description",
        accessor: "description"
      }
    ],
    []
  );

Lastly, we need to register the Table component in App.js render() method and also pass the required columns and products data as props. The overall implementation is shown in the code snippet below:

return (
    <div className="App">
      <h1>Example of React table with FakeStore API</h1>
      <Table columns={columns} data={products} />
    </div>
  );

Hence, we will get the result as shown in the demo screenshot below:

Untitled.png

Hence, we have successfully fetched data from the Fakestore API and displayed it in the table format using React table with proper configuration.

Conclusion

The main goal of this tutorial was to showcase the use of table components from the react-table package. Here, we learned how to fill the table component with dynamic data fetched from the server. The react-table package makes it easier to showcase the data in the proper tabular manner as we saw in the final result above. Likewise, we can also apply extra functionality of sorting, filtering, etc. to the table. Apply these advanced features can be your next challenge while using this react-table package in React ecosystem.

The overall source code and demo is available on Codesandbox.

Comments (0)