Enabling Resizable Columns in TanStack Table
Provide a guide on how to add and manage resizable columns in a TanStack Table using React's useState hook for dynamic width adjustments.
import { useTable } from 'react-table';
import { useMemo, useState } from 'react';
Import necessary hooks and components from 'react-table' and 'react'.
const columns = useMemo(() => [
{
Header: 'Name',
accessor: 'name',
// Enable column resizing and set initial width
enableResizing: true,
size: 200
},
{
Header: 'Age',
accessor: 'age',
// Enable column resizing and set initial width
enableResizing: true,
size: 100
}
], []);
Define the columns of the table, enabling resizing feature and setting initial size for each.
const data = useMemo(() => [...], []); // Your table data
Define the data for the table using useMemo to optimize performance.
const [columnWidths, setColumnWidths] = useState({});
Use the useState hook to manage the dynamic widths of columns.
const tableInstance = useTable({
columns,
data,
// Enable column resizing feature
enableColumnResizing: true,
// Pass dynamic column widths and setter function
initialColumnWidths: columnWidths,
onColumnWidthChange: setColumnWidths
});
Instantiate the table with column resizing functionality, passing initial widths and a function to update widths.
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = tableInstance;
Destructure necessary methods and properties from the table instance.