Mastering React Tables with useTable & useFilter for Enhanced Data Control

With a tonne of fantastic capabilities, React-Table is a fantastic headless data table component for React. Although the code samples might use some improvement, the API is clearly documented. For newbies, it can be confusing when they show numerous distinct hooks in a single example. In documentation, an SPI (Simplest Possible Implementation) is always preferred.

Setting up React Tables Project

Create a sample react app & install dependency “react-table” with below command.

npm install react-table axios

After the installation in Your Main App.js file import axios and call sample api to get the data to show into the table.

import React, { useState, useEffect, useMemo } from "react";
import axios from "axios";

Getting Started with React Tables Example

Initialize the state for the Tables data and in axios api call set the data after api response in your useEffect hook.

const [data, setData] = useState([]);
useEffect(() => {
axios("https://api.sampleapis.com/cartoons/cartoons2D")
.then((res) => {
setData(res.data);
})
.catch((err) => console.log(err))
}, []);

Now Define the columns for your table. The columns structure would be as follows:

  • Header – the name of the column
  • Accessor – key in data.
const columns = useMemo(
() => [
{
Header: "TV Show",
columns: [
{
Header: "Name",
accessor: "show.title"
},
{
Header: "Year",
accessor: "show.year"
},
{
Header: "Rating",
accessor: "show.rating"
},
{
Header: "episodes",
accessor: "show.episodes"
},

]
}
]
)

Implement useTable Hook in React Table

As we have already defined the columns and also obtained the data we wanted to show into the table , So now we can use the useTable hook and get the props we need for our table component. Below is the implementation of how we can get the table props by using useTable hook by just passing data & columns as an argument to it.

const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})

As we have now extracted table props from useTable hook now we can return our table component from our main functional component and use those props as follows.

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>
);

Thus this way we can implement the Table using react-table and its useTable hook. Next we will see How we can use the useFilter hook to filter the table data.

Hire Our Expert React Native Developers

Implementing useFilter Hook

Here for filtering we can create a new component for filtering purposes so just create a new file in your directory Filter.js. Which will be a functional component for filters UI.

Here we are creating two types of filter for the table. One will be a common input filter for all columns and a Custom select filter for the years column.

In this Filter.js file we will create a filter of type Select for year column & default search filter for other columns.

export function ColumnSearchInputFilter({
column: {
filterValue,
preFilteredRows: { length },
setFilter,
},
}) {
return (
<Input
value={filterValue || ""}
onChange={e => {
setFilter(e.target.value || undefined);
}}
placeholder={`Search ${length} records..`}
style={{ marginTop: "10px" }}
/>
);
}

export function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Use preFilteredRows to calculate the options
Options will be array of years ie [1999,2000,2001…]
const options = useMemo(() => {
const options = new Set();
preFilteredRows.forEach(row => {
options.add(row.values[id]);
});
return [...options.values()];
}, [id, preFilteredRows]);


return (
<select
value={filterValue}
onChange={e => {
setFilter(e.target.value || undefined);
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
);
}

As we have created these 2 filter UI components into the Filter.js file and now we will export that and import into our main App.js file and along with that we also need to update imports from react-table library now. We will import the useFilters hook from react-table.

import { React } from "react";
import { useTable, useFilters} from "react-table";
import { ColumnSearchInputFilter, SelectColumnFilter } from "./Filter";

Now to configure the filters we will write our useTable hooks implementation like this.

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
defaultColumn: { Filter: ColumnSearchInputFilter },
},
useFilters
);

As said before we have a custom filter of type Select for our Year column. So for this type of custom filter implementation we will modify our year column from columns array like this.

{ 
Header: "Year",
accessor: "show.year",
Filter: SelectColumnFilter,
filter: "includes",
}

This way we can configure a custom filter for the column.

Advantages of React Tables

  • React tables are lightweight and fully customizable via callbacks and props
  • It provides several features like Sort, Filter, Global Filter, Custom Filter
  • It has client-side & Server-side pagination
  • It is Simple Ui and themable
coma

Conclusion

In this tutorial, we learned about React Table library and its useTable and useFilters hook. We also learned about how to use these hooks to render a table and Implement Filtering and custom filters for columns. These powerful hooks enable efficient data manipulation and filtering, improving the user experience and providing valuable insights. By harnessing their capabilities, developers can build sophisticated and dynamic data-driven applications with ease.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!