1. Data Grid docs
  2. Rows and records

Row selection

Checkboxes on each record, a header box that selects every matching record without storing them one by one, and methods to read, set and export the selection.

Row selection lets people pick records to act on: approve these orders, export those, delete the rest. Each record gets a checkbox; with multiple selection the header box selects every record that matches the current search and filters, even a million of them, without the grid storing each one.

Open the selection example: 20,000 orders

In the grid

  • Tick a record's box to select it. With rowSelection: 'single', ticking another moves the selection.
  • Header box (multiple selection): selects every matching record. Unticking some afterwards keeps "all matching except these".
  • Space toggles the focused record. Clear selection in the footer empties it.
  • The footer counts the selected records among the matching ones.
  • Export offers Selected records next to All matching records while records are selected.
  • Separately, dragging across cells selects a range of cells: Ctrl+C (Cmd+C on a Mac) copies it as tab-separated text, and the footer shows its count, sum and average.

The selection model

type TableSelection =
  | { all: false; ids: (string | number)[] }      // these records
  | { all: true; except: (string | number)[] };   // every matching record except these

all: true follows the search and filters: change them and it covers the new matches. IDs are the records' ids: a server source's own IDs, or for local data the record's position in the data you passed (0 for the first).

From code

MemberDoes
rowSelection: 'multiple' | 'single'Option (live): adds the checkboxes
selectionChange eventAfter each change, with count when known
getSelection(), setSelection(selection)Read or replace the selection
selectRecords(ids, selected?)Selects (or with false clears) some records, keeping the others
selectAll(), clearSelection()Every matching record, or none
getSelectedIds()The selected IDs among the matching records, in display order
exportResults(format, { selected: true }), download(format, { selected: true })Export only the selected records

JavaScript

import { mountTable } from '@8sheets/data-grid';

const approve = document.querySelector('#approve');
const grid = await mountTable(document.querySelector('#orders'), {
  title: 'Orders',
  data: orders,
  rowSelection: 'multiple',
  onSelectionChange: (selection) => {
    approve.disabled = !selection.count;
    approve.textContent = `Approve ${selection.count ?? ''} orders`;
  },
});

approve.addEventListener('click', async () => {
  const ids = await grid.getSelectedIds(); // local IDs: positions in `orders`
  await fetch('/api/orders/approve', { method: 'POST', body: JSON.stringify({ ids: ids.map((i) => orders[i].id) }) });
  await grid.clearSelection();
});

// Preselect the first three records.
await grid.selectRecords([0, 1, 2]);

React

import { useMemo, useRef, useState } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';

export function Orders({ orders }) {
  const ref = useRef(null);
  const [count, setCount] = useState(0);
  const options = useMemo(() => ({ title: 'Orders', data: orders, rowSelection: 'multiple' }), [orders]);

  async function approve() {
    const ids = await ref.current.getSelectedIds();
    await fetch('/api/orders/approve', { method: 'POST', body: JSON.stringify({ ids: ids.map((i) => orders[i].id) }) });
    await ref.current.clearSelection();
  }

  return (
    <>
      <button disabled={!count} onClick={approve}>Approve {count} orders</button>
      <div style={{ height: 480 }}>
        <DataGrid ref={ref} options={options} onSelectionChange={(s) => setCount(s.count ?? 0)} />
      </div>
    </>
  );
}

Vue

<script setup>
import { computed, ref } from 'vue';
import { DataGrid } from '@8sheets/data-grid-vue';

const props = defineProps({ orders: Array });
const options = computed(() => ({ title: 'Orders', data: props.orders, rowSelection: 'multiple' }));
const dataGrid = ref(null);
const count = ref(0);

async function approve() {
  const ids = await dataGrid.value.getSelectedIds();
  await fetch('/api/orders/approve', { method: 'POST', body: JSON.stringify({ ids: ids.map((i) => props.orders[i].id) }) });
  await dataGrid.value.clearSelection();
}
</script>

<template>
  <button :disabled="!count" @click="approve">Approve {{ count }} orders</button>
  <div style="height: 480px">
    <DataGrid ref="dataGrid" :options="options" @selection-change="(s) => (count = s.count ?? 0)" />
  </div>
</template>

Angular

import { Component, Input, ViewChild } from '@angular/core';
import { DataGridComponent, DataGridOptions } from '@8sheets/data-grid-angular';

@Component({
  selector: 'app-orders',
  imports: [DataGridComponent],
  template: `
    <button [disabled]="!count" (click)="approve()">Approve {{ count }} orders</button>
    <eight-data-grid #grid [options]="options" (selectionChange)="count = $event.count ?? 0" style="height: 480px" />`,
})
export class Orders {
  @ViewChild('grid') grid!: DataGridComponent;
  count = 0;
  options: DataGridOptions = {};
  private orders: { id: string }[] = [];

  @Input() set data(orders: { id: string }[]) {
    this.orders = orders;
    this.options = { title: 'Orders', data: orders, rowSelection: 'multiple' };
  }

  async approve() {
    const ids = await this.grid.getSelectedIds();
    await fetch('/api/orders/approve', { method: 'POST', body: JSON.stringify({ ids: ids.map((i) => this.orders[Number(i)].id) }) });
    await this.grid.clearSelection();
  }
}

Cell ranges

Dragging across cells, or Shift with the arrow keys, selects a range of cells, separate from the row selection. getRange() returns it as { anchor, focus, ids, fields, values } (display text), setRange({ anchor, focus }) selects one, copyRange() copies it as tab-separated text (copyRange({ headers: true }) with the column headings first, as the context menu's Copy with headings), and the rangeChange event follows it. focusCell(id, field) and getFocusedCell() move and read the keyboard focus.

await grid.setRange({ anchor: { id: 0, field: 'Units' }, focus: { id: 4, field: 'Price' } });
const text = await grid.copyRange(); // "2\t24\n5\t3.5\n…", needs clipboard permission
grid.on('rangeChange', (range) => (sum.textContent = range ? range.values.flat().length + ' cells' : ''));

Export the selection

exportResults(format, { selected: true }) exports the selected records among the matching ones, in display order. With a server source, the export endpoint has to narrow the export itself: set selectionExport: true on remoteTableSource (or on your source), and the export request carries selection. Without it, the grid offers only All matching records.

With a server source

getSelection() always works. getSelectedIds() works for a list of IDs, but rejects for all: true: the grid doesn't hold every matching ID of a server source. Send getSelection() to your server together with getState(), and resolve "every matching record except these" there, with the same filters.

Limits

  • Selection is cleared when the grid opens other data.
  • count is left out while a server source hasn't reported its total.
  • A cell range covers drawn records; setRange can select up to about a screenful of records.