Want to skip to the implementation? Check out these React examples:
Here's how you set up your table to use cell selection features. Adding the cell selection feature enables the related APIs.
import {
useTable,
tableFeatures,
cellSelectionFeature,
} from '@tanstack/react-table'
const features = tableFeatures({ cellSelectionFeature })
const table = useTable({
features,
columns,
data,
})The cell selection feature keeps track of spreadsheet-style rectangular selections. A user can click a cell, drag across a block of cells, Shift-click to extend, and Ctrl/Cmd-click to add a second rectangle. Let's take a look at some common use cases.
The table instance already manages the cell selection state for you. You can access the selection or values derived from it through a few APIs.
console.log(table.state.cellSelection) //get the cell selection state
console.log(table.getSelectedCellCount()) //3
console.log(table.getSelectedCellIds()) //['0_firstName', '0_lastName', '1_firstName']
console.log(table.getSelectedCellRangesData()) //[[['Tanner', 'Linsley'], ['Kevin', 'Vandy']]]In event handlers or other non-render code, you can also read the current snapshot with table.atoms.cellSelection.get(). This read does not subscribe a component to future changes, so prefer table.state.cellSelection (or table.Subscribe) in render positions.
The expansion APIs (getSelectedCellIds, getSelectedCellRangesData) are memoized and pull-based. They cost nothing unless you actually call them, so a table that only highlights cells never pays to enumerate a large selection.
CellSelectionState is an array of rectangles, each stored as its two defining corners:
type CellSelectionRange = {
anchorRowId: string
anchorColumnId: string
focusRowId: string
focusColumnId: string
}
type CellSelectionState = Array<CellSelectionRange>The anchor corner is where the selection started and stays put. The focus corner is the one that moves while dragging or Shift-extending. Storing both corners, rather than a normalized min/max rectangle, is what makes Shift-extend and "collapse back to the active cell" possible.
Because ranges are only two corners, a drag across thousands of cells updates two strings rather than building a map with one entry per selected cell.
If you need access to the selection elsewhere in your application, you can own the state slice yourself. The recommended way in v9 is an external atom passed through the atoms table option.
import { useCreateAtom } from '@tanstack/react-store'
import {
useTable,
tableFeatures,
cellSelectionFeature,
type CellSelectionState,
} from '@tanstack/react-table'
const features = tableFeatures({ cellSelectionFeature })
const cellSelectionAtom = useCreateAtom<CellSelectionState>([])
const table = useTable({
features,
columns,
data,
atoms: { cellSelection: cellSelectionAtom },
})The classic controlled-state pattern also works:
const [cellSelection, setCellSelection] = useState<CellSelectionState>([])
const table = useTable({
features,
columns,
data,
state: { cellSelection },
onCellSelectionChange: setCellSelection,
})Note: a drag emits one change per cell boundary the pointer crosses, so onCellSelectionChange fires repeatedly during a drag. If you are syncing selection to a server or a URL, debounce it or commit on mouseup.
Cell selection is keyed by row id and column id, so a meaningful row id matters here for the same reason it does with row selection. Use the getRowId table option to key selection by something stable from your data.
const table = useTable({
features,
//...
getRowId: (row) => row.uuid, // use the row's uuid from your database as the row id
})Cell selection is enabled by default for every cell. Use the enableCellSelection table option to turn it off entirely, or pass a function for per-cell control.
const table = useTable({
//...
enableCellSelection: (cell) => cell.row.original.age > 18, //only adults' cells are selectable
})A column def can also opt out, which is the common case for checkbox or action columns. A column-level false wins over the table option.
columnHelper.accessor('actions', {
enableCellSelection: false, //this column can never be selected
})A cell that cannot be selected is skipped even when a rectangle is drawn straight through it, and moveCellSelection steps over its column rather than landing on it. Use cell.getCanSelect() to decide whether to attach selection handlers in your UI.
Two cell handlers drive every mouse interaction:
<td
onMouseDown={cell.getSelectionStartHandler()}
onMouseEnter={cell.getSelectionExtendHandler()}
>
<table.FlexRender cell={cell} />
</td>You do not need to handle mouseup yourself. The start handler attaches its own document-level mouseup listener and removes it when the drag ends, so releasing the pointer outside the table still finishes the drag correctly. If your table renders into another document, such as an iframe or a popout window, pass that document in: cell.getSelectionStartHandler(myDocument).
Pressing down on a cell starts a new single-cell range, and every cell the pointer then enters moves that range's focus corner. Set enableCellSelectionDrag: false to require explicit clicks instead.
Shift-clicking moves the active range's focus corner to the clicked cell, keeping its anchor fixed. The active cell therefore stays where the selection started, matching spreadsheet behavior.
The handler recognizes Shift when the event exposes either event.shiftKey or event.nativeEvent.shiftKey. You can disable range behavior or replace the detection:
const table = useTable({
// ...
enableCellRangeSelection: false,
// For example, use the platform modifier instead of Shift:
// isCellRangeSelectionEvent: event =>
// Boolean((event as React.MouseEvent).metaKey),
})Ctrl-clicking or Cmd-clicking pushes an additional rectangle onto the selection instead of replacing it. Set enableMultiCellRangeSelection: false to allow only one rectangle at a time, or override isMultiCellRangeSelectionEvent to change the modifier.
TanStack Table does not dictate how you render selected cells. These cell APIs give you everything you need:
getSelectionEdges() returns { top, right, bottom, left }, where a side is true when the neighboring cell in that direction is not itself selected. That is what lets you draw a single continuous outline around a selection, including around a union of separate rectangles, without every cell inspecting its neighbors.
function getCellClassName(cell) {
// most cells are unselected, so bail before asking for edges
if (!cell.getIsSelected()) {
return cell.getIsFocused() ? 'cell cell-focused' : 'cell'
}
const edges = cell.getSelectionEdges()
return [
'cell',
'cell-selected',
cell.getIsFocused() && 'cell-focused',
edges.top && 'cell-edge-top',
edges.right && 'cell-edge-right',
edges.bottom && 'cell-edge-bottom',
edges.left && 'cell-edge-left',
]
.filter(Boolean)
.join(' ')
}Tip: draw the outline with box-shadow: inset ... rather than border. On a border-collapse table a thicker border widens the shared grid line, which makes rows change height as cells become selected. A box-shadow never affects layout.
Cell selection ships no keyboard handling of its own. Instead it exposes imperative APIs so a dedicated library, such as TanStack Hotkeys, can drive it:
direction is 'up', 'down', 'left', or 'right'.
import { useHotkeys } from '@tanstack/react-hotkeys'
const gridRef = useRef<HTMLDivElement>(null)
useHotkeys(
[
{ hotkey: 'ArrowUp', callback: () => table.moveCellSelection('up') },
{ hotkey: 'ArrowDown', callback: () => table.moveCellSelection('down') },
{ hotkey: 'ArrowLeft', callback: () => table.moveCellSelection('left') },
{ hotkey: 'ArrowRight', callback: () => table.moveCellSelection('right') },
{
hotkey: 'Shift+ArrowUp',
callback: () => table.extendCellSelection('up'),
},
{ hotkey: 'Mod+A', callback: () => table.selectAllCells() },
{ hotkey: 'Escape', callback: () => table.resetCellSelection(true) },
],
{ target: gridRef },
)Scope the hotkeys to the grid element rather than the document, or arrow keys and Escape will hijack inputs elsewhere on the page.
getSelectedCellRangesData() returns raw values indexed as [rangeIndex][rowIndex][columnIndex]. Turning that into clipboard text is left to your application, because the delimiter, the representation of null, and any quoting rules are decisions only you can make.
function escapeTsvValue(value: unknown) {
const text = value == null ? '' : String(value)
const safeText =
typeof value === 'string' && /^[\t\r ]*[=+@-]/.test(value)
? `'${text}`
: text
// spreadsheets expect a quoted field once it contains a delimiter, a newline,
// or a quote, with inner quotes doubled
return /["\t\n\r]/.test(safeText)
? `"${safeText.replace(/"/g, '""')}"`
: safeText
}
function toTsv(ranges: Array<Array<Array<unknown>>>) {
return ranges
.map((grid) =>
grid.map((row) => row.map(escapeTsvValue).join('\t')).join('\n'),
)
.join('\n\n')
}
navigator.clipboard.writeText(toTsv(table.getSelectedCellRangesData()))Ranges store row and column ids, not positions, so they follow their corner cells rather than screen coordinates.
Because a reorder can widen a selection onto columns the user never picked, some applications prefer to clear the selection whenever the column layout changes. That is a userland decision, and one useEffect away:
const isFirstLayout = useRef(true)
useEffect(() => {
if (isFirstLayout.current) {
isFirstLayout.current = false
return
}
table.resetCellSelection(true)
}, [
table.state.columnOrder,
table.state.columnPinning,
table.state.columnVisibility,
])table.resetCellSelection() restores initialState.cellSelection. Pass true to ignore initial state and clear the selection entirely.
The selection also resets automatically whenever data changes, because new data can invalidate the row ids a range points at, or silently re-select cells if the new data happens to reuse ids. Turn that off with autoResetCellSelection: false, and note that autoResetAll overrides it.
const table = useTable({
//...
autoResetCellSelection: false, //keep ranges across data changes
})Cell selection is the feature most likely to make a large table feel slow, because a drag updates state on every cell boundary the pointer crosses. On a table with a thousand rows and a dozen columns, a naive setup re-renders twelve thousand cells per update.
The per-cell reads themselves are cheap. cell.getIsSelected() resolves the cell's row and column index and compares them against a memoized cache of the selection's bounds, which is a handful of integer comparisons. The expensive part is React reconciling every cell in the table.
table.Subscribe is the tool for this, and where you put it is what matters. The obvious placement is around the whole <tbody>:
{
/* every selection change re-renders every row */
}
;<table.Subscribe source={table.atoms.cellSelection}>
{() => (
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>...</tr>
))}
</tbody>
)}
</table.Subscribe>That works, but it re-renders the entire table body on every drag update. Instead, put a subscription on each row with a selector that returns only what changes that row's appearance. Subscribe uses useSelector under the hood, so a row whose selected value is unchanged does not re-render:
<tbody>
{table.getRowModel().rows.map((row) => (
<table.Subscribe
key={row.id}
source={table.atoms.cellSelection}
selector={(ranges) =>
rowSelectionKey(
ranges,
table.getCellSelectionBounds(),
row.getDisplayIndex(),
row.id,
)
}
>
{() => (
<tr>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className={getCellClassName(cell)}>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
)}
</table.Subscribe>
))}
</tbody>The selector needs to encode everything that changes how a row draws: whether its own cells fall inside a range, whether the rows immediately above and below do (that is what decides its top and bottom edges), and whether it owns the focused cell.
function rowSelectionKey(ranges, bounds, rowIndex, rowId) {
const active = ranges[ranges.length - 1]
let key =
ranges.length > 0 && active.anchorRowId === rowId
? `f${active.anchorColumnId}`
: ''
for (const bound of bounds) {
const self = rowIndex >= bound.minRowIndex && rowIndex <= bound.maxRowIndex
const above =
rowIndex - 1 >= bound.minRowIndex && rowIndex - 1 <= bound.maxRowIndex
const below =
rowIndex + 1 >= bound.minRowIndex && rowIndex + 1 <= bound.maxRowIndex
if (self || above || below) {
key += `|${self ? 1 : 0}${above ? 1 : 0}${below ? 1 : 0}:${bound.minColumnIndex}-${bound.maxColumnIndex}`
}
}
return key
}table.getCellSelectionBounds() is memoized, so it computes once per selection change no matter how many rows call it. Rows in the middle of a growing range produce an unchanged key, so extending a drag downward only re-renders the two rows at the moving boundary instead of all of them. On a thousand-row table this took a drag from roughly thirty-five milliseconds per update down to around ten.
Two things worth knowing about this pattern:
Leave column layout out of the selector. Pinning, reordering, and hiding columns change what a row renders, but those slices are usually part of your useTable selector already, so the parent re-renders and recreates these rows anyway. Adding them to the selection selector is redundant.
Prefer this over React.memo. A memoized row component reads its cell classes through getters like cell.getIsSelected(), which hide their state dependency from the React Compiler. With the stable row object as its only visible input, the compiler can cache the row's cells and the highlight will never move, even though React.memo re-rendered correctly. table.Subscribe avoids the problem entirely because useSelector is a dependency the compiler recognizes. See Subscribe for React Compiler Compatibility for more on this.
If your table is large enough that this is not sufficient, reach for virtualization so that only visible rows exist in the DOM at all.