Want to skip to the implementation? Check out these examples:
TanStack Table offers state and APIs helpful for implementing column pinning features in your table UI. You can implement column pinning in multiple ways. You can either split pinned columns into their own separate tables, or you can keep all columns in the same table, but use the pinning state to order the columns correctly and use sticky CSS to pin the columns to the left or right.
There are 3 table features that can reorder columns, which happen in the following order:
The only way to change the order of the pinned columns is in the columnPinning.left and columnPinning.right state itself. columnOrder state will only affect the order of the unpinned ("center") columns.
Managing the columnPinning state is optional, and usually not necessary unless you are adding persistent state features. TanStack Table will already keep track of the column pinning state for you. Manage the columnPinning state just like any other table state if you need to.
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>({
left: [],
right: [],
});
//...
const table = useReactTable({
//...
state: {
columnPinning,
//...
}
onColumnPinningChange: setColumnPinning,
//...
});
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>({
left: [],
right: [],
});
//...
const table = useReactTable({
//...
state: {
columnPinning,
//...
}
onColumnPinningChange: setColumnPinning,
//...
});
A very common use case is to pin some columns by default. You can do this by either initializing the columnPinning state with the pinned columnIds, or by using the initialState table option
const table = useReactTable({
//...
initialState: {
columnPinning: {
left: ['expand-column'],
right: ['actions-column'],
},
//...
}
//...
});
const table = useReactTable({
//...
initialState: {
columnPinning: {
left: ['expand-column'],
right: ['actions-column'],
},
//...
}
//...
});
Note: Some of these APIs are new in v8.12.0
There are a handful of useful Column API methods to help you implement column pinning features:
If you are just using sticky CSS to pin columns, you can for the most part, just render the table as you normally would with the table.getHeaderGroups and row.getVisibleCells methods.
However, if you are splitting up pinned columns into their own separate tables, you can make use of the table.getLeftHeaderGroups, table.getCenterHeaderGroups, table.getRightHeaderGroups, row.getLeftVisibleCells, row.getCenterVisibleCells, and row.getRightVisibleCells methods to only render the columns that are relevant to the current table.
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.