Skip to main content

React Table Tutorial: Project Setup and useTable (Part 1)

Page 1

React Table Tutorial: Project Setup and useTable (Part 1)

www.bacancytechnology.com


Table user interfaces are ubiquitous, mostly used and organized UI preferred by users and developers. It makes the data look simple and easily accessible. Being a ReactJS developer, you might have heard of react-table v7; few might have implemented it too. If you are looking for a tutorial explaining React Table V7 with an Example, you have chosen the right blog. I understand how challenging it could be when you are trying to learn something new, but I also know how interesting is that! Isn’t it?


Here is a tutorial series in which I would help you learn about reacttable with an example. In this series, I will explain how to implement the basics of React Table using the primary hook – useTable and then we will proceed with other hooks – useFilters, useSortBy, and usePagination Refer to the next section that includes the points covered in this tutorial – React Table Tutorial (Part 1) – Project Setup, Installation, and useTable.


Table of Contents 1. React Table v7 2. New Features in React Table v7 3. Project Setup 4. Install react-table and axios 5. React Table Example: Building a React Table demo using react-table 6. Conclusion


React Table v7


The creator of React Table – Tanner Linsley, launched React Table v7 in March 2020. We might remember using the class component of react-table, but now the library provides the Hooks-based APIs and plugins for creating a hassle-free React Table. The release is considered a significant change as the approach to create a table, table UI, and style has changed.

https://youtu.be/fwOZUU3OqmY


New Features in React Table v7


Considering React Table release note, here are the new features in React Table v7: Headless (100% customizable, Bringyour-own-UI) Lightweight (5kb – 14kb+ depending on features used and tree-shaking) Sorting (Multi and Stable) Filters Animatable Row Expansion Column Ordering Virtualizable Server-side/controlled data/state Auto out of the box, fully controllable API Extensible via a hook-based plugin system Row Selection Resizable Pivoting & Aggregation


Project Setup Create ReactJS project using the below command-

npx create-react-app react-table-demo


Install reacttable and axios Install react-table and axios

npm install react-table axios --save //npm yarn add react-table axios //yarn


React Table Example: Building a React Table demo using react-table


After done with project setup and installation, follow these steps to implement React Table Example. I’ll be writing the entire code in two files, i.e., App.js – main file TableContainer.js – having a Table component. Importing Axios and Hooks

import React, { useState, useEffect, useMemo } from "react"; import axios from "axios"; Initializing state using useState const [data, setData] = useState([]);


Defining Data: By Calling API using Axios useEffect(() => { axios("http://api.tvmaze.com/search/shows ?q=girls") .then((res) => { setData(res.data); }) .catch((err) => console.log(err)) }, []); I have called “http://api.tvmaze.com/search/shows? q=girls“ If the promise is resolved, it will execute then block, in which we will store the response in the state using setData(res.data) And if the promise is rejected, it will execute the catch block and console the error.


Defining Columns After preparing our data, let’s define the columns of the Table. The column structure would consistHeader – the name of the column Accessor – key in data. We will wrap it inside hook useMemo as far as the optimization is concerned. const columns = useMemo( () => [ { Header: "TV Show", columns: [ { Header: "Name", accessor: "show.name" }, {


Header: "Type", accessor: "show.type" }, { Header: "Language", accessor: "show.language" }, { Header: "Official Site", accessor: "show.officialSite", Cell: ({ cell: { value } }) => value ? <a href= {value}>{value}</a> : "-" }, { Header: "Rating", accessor: "show.rating.average", Cell: ({ cell: { value } }) => value || "-" }, { Header: "Status", accessor: "show.status", }, {


Header: "Premiered", accessor: "show.premiered", Cell: ({ cell: { value } }) => value || "-" }, { Header: "Time", accessor: "show.schedule.time", Cell: ({ cell: { value } }) => value || "-" }, ] } ] )


You might be wondering why I have written “show.name”, “show.type”, “show.rating.average” and so on. It is because the data is inside the show object, and for accessing the data, we will use show. as the prefix. Here is the sample of data-

Custom Cell { Header: "Official Site", accessor: "show.officialSite", Cell: (props) => { return <YourComponent {...props}/> } },


We can have the custom cell for each row as shown above. A cell has access to the values of each row; you can console props to see what it consists of. Our demo will implement the custom cell to check whether show.officalSite has the value or not. If it has the value then it will return or “-”

{ Header: "Official Site", accessor: "show.officialSite", Cell: ({ cell: { value } }) => value ? <a href={value}>{value}</a> : "-" },


useTable Hook We will create another file named – TableContainer.js in which we will build our Table component using the useTable hook. It will take two properties: data and columns, which we have defined in the above sections. data consists of the data of the API response columns is an array of objects for defining table columns. import React from "react"; import { useTable } from "react-table"; export default function Table({ columns, data }) { 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, i) => { prepareRow(row) return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { return <td {...cell.getCellProps()}> {cell.render('Cell')}</td> })} </tr> ) })} </tbody> </table> ) }


Rendering React Table Import the Table from the TableContainer.js and then render on the UI using

import Table from './TableContainer' < div className="App" > <h1><center>React Table Demo</center></h1> <Table columns={columns} data= {data} /> < /div >

After implementing the above code snippets, following your App.js and TableContainer.js will look like this –


// App.js

import React, { useState, useEffect, useMemo } from "react"; import axios from "axios"; import { useTable } from "reacttable"; import './App.css'; function Table({ columns, data }) { 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, i) => { prepareRow(row) return (


<tr {...row.getRowProps()}> {row.cells.map(cell => { return <td {...cell.getCellProps()}> {cell.render('Cell')}</td> })} </tr> ) })} </tbody> </table> ) } function App() { const [data, setData] = useState([]); useEffect(() => { axios("http://api.tvmaze.com/search/shows ?q=girls") .then((res) => { setData(res.data); })


.catch((err) => console.log(err)) }, []); const columns = useMemo( () => [ { Header: "TV Show", columns: [ { Header: "Name", accessor: "show.name" }, { Header: "Type", accessor: "show.type" }, { Header: "Language", accessor: "show.language" }, {


Header: "Official Site", accessor: "show.officialSite", Cell: ({ cell: { value } }) => value ? <a href={value}>{value}</a> : "-" }, { Header: "Rating", accessor: "show.rating.average", Cell: ({ cell: { value } }) => value || "-" }, { Header: "Status", accessor: "show.status", }, { Header: "Premiered", accessor: "show.premiered", Cell: ({ cell: { value } }) => value || "-" }, {


Header: "Time", accessor: "show.schedule.time", Cell: ({ cell: { value } }) => value || "-" }, ] } ] ) return ( <div className="App"> <h1><center>React Table Demo</center> </h1> <Table columns={columns} data={data} /> </div> ); }

export default App;


// TableContainer.js

import React from "react"; import { useTable } from "react-table"; export default function Table({ columns, data }) { 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, i) => { prepareRow(row)


return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { return <td {...cell.getCellProps()}> {cell.render('Cell')}</td> })} </tr> ) })} </tbody> </table> ) }


After running the command npm run start you will see something like this-

Here is the source code of this entire React Table demo – Github Repository So this was all about implementing the basics of React Table using useTable. I hope you have understood the example. In the next tutorial, we will learn about another hook useFilters.


Conclusion At Bacancy Technology, we have dedicated ReactJS developers who have in-depth knowledge and extensive experience in ReactJS. If you are looking for top React developers who can help you fulfill your unique business requirements, contact Bacancy Technology to hire ReactJS developer today.


Thank You

www.bacancytechnology.com


Turn static files into dynamic content formats.

Create a flipbook
React Table Tutorial: Project Setup and useTable (Part 1) by Bacancy Technology - Issuu