In web development, tables are commonly used to display structured data in a tabular format. React provides various tools and libraries to create interactive and dynamic tables. One such library is react-table, which simplifies developing and managing tables in React.
In this tutorial, we will learn how to create a table using the react-table library in a React application. We'll walk through the steps of fetching data from an API, setting up the table component, and rendering the table with sortable columns.
Prerequisites
Before starting, make sure you have the following requirements installed:
- Node.js and npm (Node Package Manager) - to set up and manage the React application.
- Basic knowledge of React - understanding React components and hooks will be helpful.
Step 1: Set Up the Project
To get started, create a new React project by running the following command in your terminal:
npx create-react-app react-table-demo
cd react-table-demo
Step 2: Install Dependencies
In this step, we'll install the required dependencies for our project. Open a terminal and run the following command inside the project directory:
npm install react-table
Step 3: Fetch Data
In this step, we'll fetch data from an API and store it in the parent component's state. In this code, we define the App component as the parent component. It fetches data from the API using the fetchData function when the component mounts. The fetched data is stored in the data state variable and passed to the Table component as a prop.
import React, { useState, useEffect } from "react";
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await fetch("https://cities-qd9i.onrender.com/agents");
const agents = await response.json();
setData(agents);
} catch (error) {
console.error("Error fetching data:", error);
}
};
That is how looks the JSON data.
{
"agents": [
{
"id": 1,
"first_name": "Alysia",
"last_name": "Ivashechkin",
"email": "aivashechkin0@example.com",
"phone": "(424) 8787997",
"image": "https://picsum.photos/400",
"state": "California",
"city": "Los Angeles",
"address": "2 Vermont Junction"
},
{
"id": 2,
"first_name": "Alicia",
"last_name": "Sworder",
"email": "asworder1@mozilla.com",
"phone": "(804) 8988278",
"image": "https://picsum.photos/400",
"state": "Virginia",
"city": "Richmond",
"address": "362 Hoffman Court"
}
]
}
Step 4: Create the Table Component
In this step, we'll create the Table component that will render the table using the react-table library.
The useMemo hook is used in this code to memoize the columns configuration so that it is only calculated once and avoids unnecessary recalculations and re-renders.
import React, { useMemo } from "react";
import { useTable } from "react-table";
import "./Table.css";
const Table = ({ data }) => {
const columns = useMemo(
() => [
{ Header: "ID", accessor: "id" },
{ Header: "First Name", accessor: "first_name" },
{ Header: "Last Name", accessor: "last_name" },
{ Header: "Email", accessor: "email" },
{ Header: "Phone", accessor: "phone" },
{ Header: "State", accessor: "state" },
{ Header: "City", accessor: "city" },
{ Header: "Address", accessor: "address" }
],
[]
);
Step 5: Creating the Table Instance
Using the useTable hook, we create a table instance by passing the columns and data as arguments. The hook returns several properties and methods we can use to render and interact with the table.
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({ columns, data });
Step 6. Rendering the Table
We render the table. We use the spread operator (...) to apply the getTableProps function to the
Top comments (0)