Photo by Lautaro Andreani on Unsplash
How to Make a Table Component with Filtering and Sorting Capabilities Using the react-table Library and the useMemo Hook
Creating a table with filtering and sorting capabilities using the react-table library and the useMemo
hook is a straightforward process that can be completed in just a few steps. Here's a tutorial on how to create a table with react-table that is able to do filtering and sorting, and use useMemo
to memoize the data:
- Begin by setting up a new React project and installing the react-table library using npm or yarn:
npm install react-table
#or
yarn add react-table
- Next, import the
useMemo
hook and the react-table components that you need in your React component. At a minimum, you'll need to import theTable
component:
import { useMemo } from 'react';
import { Table } from 'react-table';
- Decide on the data that you want to display in your table. This could be hard-coded data, or data that you retrieve from an API or database. For example, you might have an array of objects like this:
const data = [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Charlie", age: 35 }
]
- In your React component, By using
useMemo
to memoize the data and columns of your table, you can help to improve the performance of your application by avoiding unnecessary re-renders when the data or columns change:
const memoizedData = useMemo(() => data, [data]);
const memoizedColumns = useMemo(() => [
{
Header: "ID",
Cell: row => row.original.id
},
{
Header: "Name",
Cell: row => row.original.name
},
{
Header: "Age",
Cell: row => row.original.age
}
], []);
- You will also need to define the filter components that you want to use. For example, you might define a
SelectColumnFilter
component like this:
function SelectColumnFilter({ column: { setFilter, filterValue, preFilteredRows, id } }) {
// Calculate the options for the select dropdown
const options = React.useMemo(() => {
const options = new Set();
preFilteredRows.forEach(row => {
options.add(row.values[id]);
});
return [...options.values()];
}, [id, preFilteredRows]);
// Render the select dropdown
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>
);
}
- Finally, add the
table
component to your component's render method, passing in thememoizedData
andmemoizedColumns
props, and setting thefilterable
andsortable
props totrue
And that's it! You should now have a functioning table that displays your data and is able to do filtering and sorting. You can customize the appearance and behavior of your table using the various props available on the Table
component, such as defaultSortDesc
, defaultSorted
, resizable
, and pagination
.