Basic Setup for React TanStack Table
Initialize a React TanStack Table component with basic configurations, including setting up columns and data.
import { useState } from 'react';
import { createColumnHelper, useReactTable } from '@tanstack/react-table';
Import necessary hooks from React and functions from TanStack Table.
const columnHelper = createColumnHelper();
Initialize the column helper utility.
const defaultData = [{ studentId: 1111, name: 'Bahar Constantia', dateOfBirth: '1984-01-04', major: 'Business' }];
Define the default data for the table.
const columns = [
columnHelper.accessor('studentId', { header: 'Student ID' }),
columnHelper.accessor('name', { header: 'Full Name' }),
columnHelper.accessor('dateOfBirth', { header: 'Date Of Birth' }),
columnHelper.accessor('major', { header: 'Major' }),
];
Define the columns for the table using the column helper.
function DataTable() {
const [data, setData] = useState(defaultData);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div>{table.getRowModel().rows.map(row => (
<div key={row.id}>{row.original.name}</div>
))}</div>
);
}
Define a functional component that renders the table. It uses the useState hook for data management and useReactTable hook to create the table instance.