Blog>
Snippets

Custom Row Selection Logic

Showcase custom logic for enabling multiple row selections within a React TanStack Table, incorporating shift-click for range selection.
const [selectedRows, setSelectedRows] = React.useState({});
Initialize the state to store selected rows. It's an object to quickly check if a row is selected.
const toggleRowSelected = (rowIndex) => {
  setSelectedRows(prev => {
    const newSelectedRows = { ...prev };
    if (newSelectedRows[rowIndex]) {
      delete newSelectedRows[rowIndex];
    } else {
      newSelectedRows[rowIndex] = true;
    }
    return newSelectedRows;
  });
};
Function to toggle the selection of a row. It updates the state with the selected row's index.
const handleShiftClick = (rowIndex) => {
  const allRows = Object.keys(selectedRows).map(Number).sort((a, b) => a - b);
  if (allRows.length > 0) {
    const lastSelectedRowIndex = allRows[allRows.length - 1];
    const start = Math.min(rowIndex, lastSelectedRowIndex);
    const end = Math.max(rowIndex, lastSelectedRowIndex);
    const newSelectedRows = { ...selectedRows };
    for (let i = start; i <= end; i++) {
      newSelectedRows[i] = true;
    }
    setSelectedRows(newSelectedRows);
  } else {
    toggleRowSelected(rowIndex);
  }
};
Handles range selection of rows when the user holds the 'Shift' key and clicks on a row. It selects all rows between the last selected row and the current clicked row.
const handleRowClick = (rowIndex, event) => {
  if (event.shiftKey) {
    handleShiftClick(rowIndex);
  } else {
    toggleRowSelected(rowIndex);
  }
};
Integrates shift-click logic with the standard click logic for row selection.