Adaptable

#useCellSelection

useCellSelection() gives you the selected cells of the current view — their row ids, column ids, values and data types — and re-renders your component when the selection changes. Use it to build summaries, charts or actions over the user's selection.

Note

Cell selection needs the view's selection.mode to be 'multi-cell' (the default) — see Multi-cell selection. For selected rows, use useRowSelection.

#Return value

The hook returns null when no cell is selected. Otherwise it returns an object with:

  • columnIds — the ids of every column that has at least one selected cell. The selection does not have to be contiguous.

  • positions — one array per row that has a selection. Each inner array lines up with columnIds. A selected cell is an object with:

    • rowId — the primary key of the row.
    • value — the cell value.
    • columnId — the id of the column.
    • columnDataType — the data type of the column ('text', 'number', 'date', …).

    A cell in columnIds that is not selected in that row is an empty string.

useCellSelection return value
{
  columnIds: ['firstName', 'salary', 'country'],
  positions: [
    [
      { rowId: 1, value: 'Emma', columnId: 'firstName', columnDataType: 'text' },
      { rowId: 1, value: 89000, columnId: 'salary', columnDataType: 'number' },
      '', // country is not selected in this row
    ],
    [
      { rowId: 3, value: 'Ines', columnId: 'firstName', columnDataType: 'text' },
      '', // salary is not selected in this row
      { rowId: 3, value: 'Japan', columnId: 'country', columnDataType: 'text' },
    ],
  ],
}

#Usage

Using useCellSelection
import { Adaptable, useCellSelection } from '@adaptabletools/datagrid-react';

function SelectionSummary() {
  const cellSelection = useCellSelection();

  if (!cellSelection) {
    return <div>No cell selection</div>;
  }

  const { columnIds, positions } = cellSelection;
  // one entry per selected row, with the values in columnIds order
  const rows = positions.map((row) =>
    row.map((cell) => (typeof cell === 'object' ? cell.value : null)),
  );

  return <Chart columns={columnIds} rows={rows} />;
}

function App() {
  return (
    <Adaptable.Provider {...props}>
      <SelectionSummary />
      <Adaptable.UI />
    </Adaptable.Provider>
  );
}
Note

The raw selection (row id and column id pairs) is also part of the view state, under selection.value — see useCurrentViewState. This hook resolves it to values for you.

#
Summarizing the selected cells

The panel above the grid reads useCellSelection() and shows how many cells are selected, in which columns, and the sum of the numeric ones. The view starts with a few cells selected.

Click and shift-click (or cmd/ctrl-click) cells to change the selection.

open
loading demo…