Integrating TanStack Table with React and TypeScript
Provide an example of setting up TanStack Table in a React component with TypeScript, including the basic configuration for displaying data.
import React, { useMemo } from 'react';
import { useTable } from 'react-table';
import { Column } from 'react-table';
interface Data {
id: number;
firstName: string;
lastName: string;
age: number;
}
const TableComponent: React.FC = () => {
const data = useMemo<Data[]>(
() => [
{ id: 1, firstName: 'John', lastName: 'Doe', age: 28 },
{ id: 2, firstName: 'Jane', lastName: 'Doe', age: 22 },
// Add more data here
],
[]
);
const columns = useMemo<Column<Data>[]>(
() => [
{
Header: 'ID',
accessor: 'id', // accessor is the "key" in the data
},
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
{
Header: 'Age',
accessor: 'age',
},
// Add more columns here
],
[]
);
const tableInstance = useTable<Data>({ columns, data });
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = tableInstance;
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 => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
};
export default TableComponent;
This code snippet demonstrates how to integrate TanStack Table (formerly known as react-table) with React and TypeScript for creating a functional data table. It starts by importing necessary functions and types from React and react-table. It defines an interface 'Data' to type the table data. useMemo hook is used to memorize the data and columns to avoid unnecessary re-renders. useTable hook from react-table is utilized to create a table instance with typed data and columns. Finally, it renders a table with headers and rows mapped from the provided data.