The complete guide to building a smart data table in React
Brian Neville-O'Neill
Posted on December 2, 2019
Written by Paramanantham Harrison✏️
Table UIs are very common in web products because they’re one of the easiest way to organize complex data in the UI. Many companies use data tables to show complex reports.
Some common use cases for table UIs include displaying data for finance reports, sports leaderboards, and pricing and comparison pages.
Some products that use data tables extensively include:
- Airtable
- Asana List View
- Asana Timeline
- Google Sheets
- Notion Table
Table UI features
Basic features of a data table UI include:
- Uncompromised UX and UI. Clearly understandable typography and custom elements inside the table UI
- Remote data calls to load data
- Searching the table or specific columns
- Basic filtering and sorting options
Advanced features in a data table UI include:
- Custom sorting and filtering options for columns based on data types (numbers, string, boolean, select input, etc.)
- Pagination support or infinitely long tables (performance for very large datasets)
- Showing and hiding columns
- Support for inline editing data for a column
- Support for editing a complete row of data through a modal/details panel
- Fixed headers and fixed columns for easy viewing of data
- Support for multiple devices (responsiveness)
- Resizable columns to accommodate long data points inside a column (e.g., multi-line comments)
- Horizontal and vertical scroll support
- Expandable rows to show complete data about the row
Common UX challenges in a table UI
UI-wise, data tables are one of the best options to show complex data in an organized way. But UX-wise, it’s tricky — it can easily get out of hand when you support multiple devices. Some of the UX challenges for tables include:
Responsiveness
It’s difficult to make a table responsive without changing the layout to suit smaller screen sizes.
Scrolling
A table might need scrolling in both directions. Default browser scrollbars will work well for full-width tables, but most are of a custom width. Custom scrollbars are very tricky to support on both touch and non-touch screens.
Managing column width
Managing the width of the column based on data length is tricky. It often causes UX glitches when we load dynamic data in the table. Each time the data changes, it resizes the column width and causes an alignment glitch. We need to be careful in handling those issues while designing the UX.
Top libraries for data tables in React
In this article, we will learn to build a simple Airtable clone using React. We will explore some of the open-source React table libraries and choose the best one for our use case.
react-table
react–table is one of the most widely used table libraries in React. It has more than 7k stars on GitHub, receives frequent updates, and supports Hooks. React table library is very lightweight and offers all the basic features necessary for any simple table.
When to use react-table
When your table UI needs:
- Basic features like sorting, filtering, and pagination
- Custom UI design for the table without affecting functionality
- Easy extensibility; you can build your own features on top of the library using custom plugin Hooks
When not to use react-table
When you need:
- Default support for fixed headers and columns
- Out-of-the-box support for horizontal and vertical scroll for both touch and non-touch devices. react-table doesn’t dictate the UI; it’s headless, so it’s our responsibility to define the UI based on our need
- Support for inline editing of columns. We can achieve it in react-table, but it’s out of scope for our table to do it. We need to create a plugin or component on top of it to support such features. react-table stays true to its name and is best for rendering simple tables
- Infinitely long tables like a Google Sheet; performance-wise, it can’t handle such a large list. It works well for medium-sized tables but not for long ones
Use cases
- For simple tables that need basic features like searching, sorting, filtering, etc.
- Sports leaderboards/statistics, finance data table with custom elements
react-data-grid
react-data-grid is another library used for creating smart tables. It has nearly 4k GitHub stars and is well maintained.
When to use react-data-grid
When your data table needs:
- Basic features like grouping columns, sorting, searching, and filtering
- Inline editing of columns
- A dropdown inside a column (like Google Sheets) or any custom input elements inside the column
- Support for expanding columns to show more data
- To be fine-tuned for performance, i.e., it supports virtual rendering for infinitely long table rows
- Support for empty state when there are no rows
When not to use react-data-grid
react-data-grid covers almost all the basic needs for a data table. However, it doesn’t support pagination by default, so if your table requires pagination, you need to manually implement and handle it. By default, react-data-grid supports longer table UIs and is optimized for performance, so pagination might not be necessary unless the UX demands it.
It also uses Bootstrap for styling. You can still use react-data-grid without it, but then you’d need to add your own styling for the table. It’s not easily customizable compared to react-table, which allows you to create the table structure. Here in react-data-grid, the library creates the table UI, so it’s not great for UI-heavy custom pages.
While the above points aren’t exactly shortcomings, they’re nice to know about before you start using react-data-grid.
Use cases
Intermediate needs when you have to build a mini editable data table similar to Google Sheets or Airtable with nice UX.
react-datasheet
react–datasheet is similar to react-data-grid. It has a similar number of GitHub stars and contributions and is likewise a well-maintained library.
It primarily focuses on creating your own Google Sheets-like application. It has basic features inbuilt to create such UX-heavy applications. Once again, it might not be suitable for creating general-purpose page UI with tables.
Unlike react-data-grid, however, it is not optimized for large datasets, so use it for small applications that need Sheets-like functionality. It has only this one use case, and its features are very limited compared to those of react-data-grid.
react-virtualized
As the name itself implies, react-virtualized is heavily optimized for performance when the dataset is large. This library is not exactly a table library; it does much more. It is exclusively for displaying large datasets on the UI in different formats, like grid, table, and list.
I am not going very deep into details on this library since it does more than what we need.
When to use react-virtualized
When your data is very large, rendering performance is the key metric for the table; if that’s the case, go for react-virtualized. For normal use cases, this library would be overkill, and the API would be too advanced.
Use cases
Use react-virtualized for custom timelines, charts involving infinitely long calendars, and heavy UI elements for your large dataset.
So which React table library should you choose?
- For a simple page with limited data, custom styles, and minimum interactivity like sorting and filtering, use react_–_table
- To build a mini Google Sheets-like application, but with limited data, use react-data-grid or react-datasheet
- For a Google Sheets- or Airtable-like application with a large dataset, use react-data-grid
- When you’re working with a very large dataset and you need a custom UI that offers tables, grids, and many more options, choose react_–_virtualized
When to build your own table UI
There are certain scenarios in which you might want to build your own table UI:
- When your table is just a showcase that doesn’t have many interactions
- When you need a custom UI for the table
- When you need your table to be very lightweight without any functionality
Use cases
- Product/marketing pages with tables for comparison
- Pricing tables
- Simple tables with custom styling that don’t require many interactions for the columns other than simple popover text
Building a smart table UI using React
Enough theory — let’s start building a simple table UI with basic functionalities like sorting and searching using react-table
. We are going to build this simple table. It has basic search and sorting functionality.
First, create a React app using create-react-app:
npx create-react-app react-table-demo
Call the TV Maze API for table data
This is the API endpoint. We are going to call and fetch the shows’ information with the search term “snow.”
In order to call the API, let’s install axios
:
yarn add axios
// App.js
import React, { useState, useEffect } from "react";
import Table from "./Table";
import "./App.css";
function App() {
// data state to store the TV Maze API data. Its initial value is an empty array
const [data, setData] = useState([]);
// Using useEffect to call the API once mounted and set the data
useEffect(() => {
(async () => {
const result = await axios("https://api.tvmaze.com/search/shows?q=snow");
setData(result.data);
})();
}, []);
return (
<div className="App"></div>
);
}
export default App;
We create a state called data
, and once the component gets mounted, we call the API using Axios and set the data
.
Render a simple table UI using the data
Now we’ll add react-table:
yarn add react-table
react-table uses Hooks. It has a main table Hook called useTable
, and it has a plugin system to add plugin Hooks. Thus, react-table is easily extensible based on our custom need.
Let’s create the basic UI with the useTable
Hook. We will create a new Table
component that will accept two props: data
and columns
. data
is the data we got through the API call, and columns
is the object to define the table columns (headers, rows, how the row will be shown, etc.). We will see it in code shortly.
// Table.js
export default function Table({ columns, data }) {
// Table component logic and UI come here
}
// App.js
import React, { useMemo, useState, useEffect } from "react";
import Table from "./Table";
function App() {
/*
- Columns is a simple array right now, but it will contain some logic later on. It is recommended by react-table to Memoize the columns data
- Here in this example, we have grouped our columns into two headers. react-table is flexible enough to create grouped table headers
*/
const columns = useMemo(
() => [
{
// first group - TV Show
Header: "TV Show",
// First group columns
columns: [
{
Header: "Name",
accessor: "show.name"
},
{
Header: "Type",
accessor: "show.type"
}
]
},
{
// Second group - Details
Header: "Details",
// Second group columns
columns: [
{
Header: "Language",
accessor: "show.language"
},
{
Header: "Genre(s)",
accessor: "show.genres"
},
{
Header: "Runtime",
accessor: "show.runtime"
},
{
Header: "Status",
accessor: "show.status"
}
]
}
],
[]
);
...
return (
<div className="App">
<Table columns={columns} data={data} />
</div>
);
}
export default App;
Here in the columns, we can create multiple groups of headers and columns. We created two levels.
All the columns also have an accessor, which is the data we have in the data
object. Our data is inside the show
object in the array — that’s why all our accessors have show.
as a prefix.
// sample data array looks like this
[
{
"score": 17.592657,
"show": {
"id": 44813,
"url": "http://www.tvmaze.com/shows/44813/the-snow-spider",
"name": "The Snow Spider",
"type": "Scripted",
"language": "English",
"genres": [
"Drama",
"Fantasy"
],
"status": "In Development",
"runtime": 30,
"premiered": null,
"officialSite": null,
"schedule": {
"time": "",
"days": [
]
}
...
},
{
// next TV show
}
...
]
Let’s finish our Table
component:
// Table.js
import React from "react";
import { useTable } from "react-table";
export default function Table({ columns, data }) {
// Use the useTable Hook to send the columns and data to build the table
const {
getTableProps, // table props from react-table
getTableBodyProps, // table body props from react-table
headerGroups, // headerGroups if your table have groupings
rows, // rows for the table based on the data passed
prepareRow // Prepare the row (this function need to called for each row before getting the row props)
} = useTable({
columns,
data
});
/*
Render the UI for your table
- react-table doesn't have UI, it's headless. We just need to put the react-table props from the Hooks, and it will do its magic automatically
*/
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>
);
}
We will pass the columns
and data
to useTable
. The Hook will return the necessary props for the table, body, and transformed data to create the header and cells. The header will be created by iterating through headerGroups
, and the rows for the table body will be created by looping through rows
.
{rows.map((row, i) => {
prepareRow(row); // This line is necessary to prepare the rows and get the row props from react-table dynamically
// Each row can be rendered directly as a string using the react-table render method
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
In this way, we rendered the cell and the header. But our cell
values are just strings, and even the array values get converted into comma-separated string values. For example:
// Genres array
show.genres = [
'Comedy',
'Sci-fi',
]
In the table, it will simply render as a comma-separated string, e.g., Comedy,Sci-fi
. At this point, our app should look like this:
Custom styling in react-table
This is a fine table for most use cases, but what if we need custom styles? react-table allows you to define custom styles for each cell. It can be defined like this in the column
object. Let’s create a badge-like custom element to show each genre.
// App.js
import React, { useMemo } from "react";
...
// Custom component to render Genres
const Genres = ({ values }) => {
// Loop through the array and create a badge-like component instead of comma-separated string
return (
<>
{values.map((genre, idx) => {
return (
<span key={idx} className="badge">
{genre}
</span>
);
})}
</>
);
};
function App() {
const columns = useMemo(
() => [
...
{
Header: "Details",
columns: [
{
Header: "Language",
accessor: "show.language"
},
{
Header: "Genre(s)",
accessor: "show.genres",
// Cell method will provide the cell value, we pass it to render a custom component
Cell: ({ cell: { value } }) => <Genres values={value} />
},
{
Header: "Runtime",
accessor: "show.runtime",
// Cell method will provide the value of the cell, we can create custom element for the Cell
Cell: ({ cell: { value } }) => {
const hour = Math.floor(value / 60);
const min = Math.floor(value % 60);
return (
<>
{hour > 0 ? `${hour} hr${hour > 1 ? "s" : ""} ` : ""}
{min > 0 ? `${min} min${min > 1 ? "s" : ""}` : ""}
</>
);
}
},
{
Header: "Status",
accessor: "show.status"
}
]
}
],
[]
);
...
}
...
In the example, we access the value through the Cell
method and then return either the computed value or custom component.
For Runtime , we compute the number of hours and return the custom value. For Genres , we loop and send the value to a custom component and that component creates a badge-like element.
It’s very easy to customize the look and feel in react-table. After this step, our table UI will look like this:
In this way, we can customize the style for each cell based on the need. You can show any custom element for each cell based on the data value.
Add search functionality
Let’s add a bit more functionality to our table. If you look at the demo page for react-table, they already provide everything you need to create a custom smart table. Just one thing is missing in their demo: global search functionality. So I decided to create that using the useFilters
plugin Hook from react-table.
First, let’s create a search input in Table.js
:
// Table.js
// Create a state
const [filterInput, setFilterInput] = useState("");
// Update the state when input changes
const handleFilterChange = e => {
const value = e.target.value || undefined;
setFilterInput(value);
};
// Input element
<input
value={filterInput}
onChange={handleFilterChange}
placeholder={"Search name"}
/>
It’s straightforward, simple state to manage the input state. But now, how to pass this filter value to our table and filter the table rows?
For that, react-table has a nice Hook plugin called useFilters
.
// Table.js
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setFilter // The useFilter Hook provides a way to set the filter
} = useTable(
{
columns,
data
},
useFilters // Adding the useFilters Hook to the table
// You can add as many Hooks as you want. Check the documentation for details. You can even add custom Hooks for react-table here
);
In our example, we are going to set the filter only for the Name
column. In order to filter the name, when the input value changes, we need to set our first param as the column accessor or ID value and our second param as the search filter value.
Let’s update our handleFilterChange
function:
const handleFilterChange = e => {
const value = e.target.value || undefined;
setFilter("show.name", value); // Update the show.name filter. Now our table will filter and show only the rows which have a matching value
setFilterInput(value);
};
This is how the UI looks after the search implementation:
This is a very basic example for filters, and there are several options provided by the react-table API. You can check out the API documentation here.
Add sorting to the table
Let’s implement one more basic functionality for our table: sorting. Let’s allow sorting for all columns. Again, it’s very simple — same as for filtering. We need to add a plugin Hook called useSortBy
and create the style to show the sorting icon in the table. It will automatically handle the sorting in ascending/descending orders.
// Table.js
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setFilter
} = useTable(
{
columns,
data
},
useFilters,
useSortBy // This plugin Hook will help to sort our table columns
);
// Table header styling and props to allow sorting
<th
{...column.getHeaderProps(column.getSortByToggleProps())}
className={
column.isSorted
? column.isSortedDesc
? "sort-desc"
: "sort-asc"
: ""
}
>
{column.render("Header")}
</th>
Based on the sorting, we add the class names sort-desc
or sort-asc
. We also add the sorting props to the column header.
{...column.getHeaderProps(column.getSortByToggleProps())}
This will automatically allow sorting for all columns. You can control that by disabling sorting in specific columns by using the disableSortBy
option on a column. In our example, we allowed sorting on all columns. You can play around with the demo.
This is how the UI looks like after our sorting implementation:
Of course, you can extend this demo even further — let me know if you need help in the comments section. Some ideas to extend it include:
- Filter multiple columns using a global filter. ( Hint: Use
setAllFilters
instead ofsetFilter
) - Create pagination and call more data to load for the table
- Allow sorting only for specific fields (disable
sortby
for columns) - Instead of passing a hardcoded search value to TV Maze API, create an input to search the TV Maze API directly (i.e., remove client-side filtering and add server-side searching of TV shows through the API and change data)
Check out react-table’s extensive example page to extend this demo. They have a very good kitchen sink to play around with, and it provides solutions for most use cases.
Conclusion
This is how the final demo looks after we added sorting. You can play around with the demo and check out the codebase for it here.
We have learned how to build a table UI using React. It’s not difficult to create your own table for basic use cases, but make sure to not reinvent the wheel wherever possible. Hope you enjoyed learning about table UIs — let me know about your experience with tables in the comments.
Editor's note: Seeing something wrong with this post? You can find the correct version here.
Plug: LogRocket, a DVR for web apps
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
Try it for free.
The post The complete guide to building a smart data table in React appeared first on LogRocket Blog.
Posted on December 2, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.