Setting up Basic Column Ordering in React TanStack Table
Implement a basic React TanStack Table with column ordering using 'useColumnOrder' to allow users to rearrange columns via drag-and-drop.
import { useTable, useColumnOrder } from '@tanstack/react-table';
Import necessary hooks from '@tanstack/react-table'.
const columns = React.useMemo(() => [
{ accessor: 'col1', Header: 'Column 1' },
{ accessor: 'col2', Header: 'Column 2' },
{ accessor: 'col3', Header: 'Column 3' },
], []);
Define the columns for the table. Each column requires an accessor and a Header.
const data = React.useMemo(() => [
{ col1: 'Data 1', col2: 'Data 2', col3: 'Data 3' },
{ col1: 'Data 4', col2: 'Data 5', col3: 'Data 6' },
{ col1: 'Data 7', col2: 'Data 8', col3: 'Data 9' },
], []);
Define the data for the table. Data should be in an array of objects format.
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setColumnOrder,
} = useTable({ columns, data }, useColumnOrder);
Create the Table component, initialize useTable hook with useColumnOrder plugin.
const changeOrder = () => {
setColumnOrder(['col3', 'col2', 'col1']);
};
Define a function to change the order of columns. This example changes the order manually.
return (
<>
<button onClick={changeOrder}>Change Column Order</button>
<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>
</>
);
Render the table with a button to change column orders. Applies necessary props from useTable.
}
Close the Table component function.
function App() {
return <Table columns={columns} data={data} />;
}
Define an App component that renders the Table with columns and data.