Skip to content

Server-side row selection

Added in Handsontable 19.0.0

Select rows across pages of server-side data, and send the selection to your server, even when it covers rows the grid never loaded.

Overview

With the DataProvider plugin, the grid holds one page of rows at a time. Every page change replaces the data. The RowSelection plugin handles this in two ways:

  • It keeps the selection by row id, which comes from the dataProvider.rowId option. A row you select on page 1 is still selected when you come back from page 3.
  • A “select all” doesn’t load every row. It records “every row matching the current query”, and keeps the rows you deselect afterward as exceptions.

For row selection on a grid with local data, see Row selection.

Enable server-side row selection

Enable the rowSelection option on a grid that uses the dataProvider option. No extra configuration is needed: the rowId option that dataProvider already requires identifies the rows.

In the following example:

  • Select a few orders, move to another page, and come back. The selection stays.
  • Click the “select all” checkbox. Every order is selected, including the orders on pages you haven’t opened.
  • Cancelled orders can’t be selected.
  • The line under the grid shows the selection the way you send it to your server.
JavaScript
import { useRef } from 'react';
import { HotTable } from '@handsontable/react-wrapper';
import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modules
registerAllModules();
const STATUSES = ['Pending', 'Paid', 'Shipped', 'Cancelled'];
const CUSTOMERS = ['Harbor Goods', 'Alpine Supply Co.', 'Cascade Distributors', 'Summit Trading', 'Nordic Traders'];
// An in-memory "server" with 40 orders. Replace it with requests to your API.
const serverOrders = Array.from({ length: 40 }, (_, index) => ({
id: 1001 + index,
customer: CUSTOMERS[index % CUSTOMERS.length],
status: STATUSES[index % STATUSES.length],
total: 25 + ((index * 37) % 400),
}));
const fetchOrders = async ({ page, pageSize }) => ({
rows: serverOrders.slice((page - 1) * pageSize, page * pageSize),
totalRows: serverOrders.length,
});
// The React wrapper calls `updateSettings` after every HotTable render. This
// object is defined once, so a render passes the same object again and
// nothing is fetched. The selection status is written through a DOM ref so a
// checkbox click does not re-render HotTable.
const dataProvider = {
// the row selection keeps rows by this id, so it survives page changes
rowId: 'id',
fetchRows: fetchOrders,
onRowsCreate: async () => {},
onRowsUpdate: async () => {},
onRowsRemove: async () => {},
};
const ExampleComponent = () => {
const hotRef = useRef(null);
const outputRef = useRef(null);
return (
<>
<HotTable
// licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/
ref={hotRef}
dataProvider={dataProvider}
columns={[
{ data: 'id', title: 'Order', readOnly: true },
{ data: 'customer', title: 'Customer' },
{ data: 'status', title: 'Status' },
{ data: 'total', title: 'Total', type: 'numeric' },
]}
colHeaders={true}
rowHeaders={true}
// reach the header checkboxes with the arrow keys, toggle them with Space
navigableHeaders={true}
pagination={{ pageSize: 10 }}
height="auto"
// enable the `RowSelection` plugin
rowSelection={{
// cancelled orders can't be selected
isRowSelectable: (rowData) => rowData.status !== 'Cancelled',
}}
afterRowSelectionChange={() => {
const rowSelection = hotRef.current?.hotInstance?.getPlugin('rowSelection');
if (rowSelection && outputRef.current) {
// send this object to your server, which applies it to the rows it did not send
outputRef.current.textContent = `${rowSelection.getSelectedCount()} selected: ${JSON.stringify(rowSelection.getServerSelection())}`;
}
}}
autoWrapRow={true}
autoWrapCol={true}
/>
<output className="console" ref={outputRef}>
0 selected
</output>
</>
);
};
export default ExampleComponent;
TypeScript
import { useRef } from 'react';
import { HotTable, HotTableRef } from '@handsontable/react-wrapper';
import { registerAllModules } from 'handsontable/registry';
import type { DataProviderQueryParameters } from 'handsontable/plugins/dataProvider';
// register Handsontable's modules
registerAllModules();
type Order = { id: number; customer: string; status: string; total: number };
const STATUSES = ['Pending', 'Paid', 'Shipped', 'Cancelled'];
const CUSTOMERS = ['Harbor Goods', 'Alpine Supply Co.', 'Cascade Distributors', 'Summit Trading', 'Nordic Traders'];
// An in-memory "server" with 40 orders. Replace it with requests to your API.
const serverOrders: Order[] = Array.from({ length: 40 }, (_, index) => ({
id: 1001 + index,
customer: CUSTOMERS[index % CUSTOMERS.length],
status: STATUSES[index % STATUSES.length],
total: 25 + ((index * 37) % 400),
}));
const fetchOrders = async({ page, pageSize }: DataProviderQueryParameters) => ({
rows: serverOrders.slice((page - 1) * pageSize, page * pageSize),
totalRows: serverOrders.length,
});
// The React wrapper calls `updateSettings` after every HotTable render. This
// object is defined once, so a render passes the same object again and
// nothing is fetched. The selection status is written through a DOM ref so a
// checkbox click does not re-render HotTable.
const dataProvider = {
// the row selection keeps rows by this id, so it survives page changes
rowId: 'id',
fetchRows: fetchOrders,
onRowsCreate: async() => {},
onRowsUpdate: async() => {},
onRowsRemove: async() => {},
};
const ExampleComponent = () => {
const hotRef = useRef<HotTableRef>(null);
const outputRef = useRef<HTMLOutputElement>(null);
return (
<>
<HotTable
// licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/
ref={hotRef}
dataProvider={dataProvider}
columns={[
{ data: 'id', title: 'Order', readOnly: true },
{ data: 'customer', title: 'Customer' },
{ data: 'status', title: 'Status' },
{ data: 'total', title: 'Total', type: 'numeric' },
]}
colHeaders={true}
rowHeaders={true}
// reach the header checkboxes with the arrow keys, toggle them with Space
navigableHeaders={true}
pagination={{ pageSize: 10 }}
height="auto"
// enable the `RowSelection` plugin
rowSelection={{
// cancelled orders can't be selected
isRowSelectable: (rowData: unknown) => (rowData as Order).status !== 'Cancelled',
}}
afterRowSelectionChange={() => {
const rowSelection = hotRef.current?.hotInstance?.getPlugin('rowSelection');
if (rowSelection && outputRef.current) {
// send this object to your server, which applies it to the rows it did not send
outputRef.current.textContent = `${rowSelection.getSelectedCount()} selected: ${JSON.stringify(rowSelection.getServerSelection())}`;
}
}}
autoWrapRow={true}
autoWrapCol={true}
/>
<output className="console" ref={outputRef}>0 selected</output>
</>
);
};
export default ExampleComponent;

Send the selection to your server

The grid can’t list rows it never loaded, so getSelectedRowsData() returns only the loaded rows. To act on the whole selection, call getServerSelection() and send its result to your server:

const rowSelection = hot.getPlugin('rowSelection');
const selection = rowSelection.getServerSelection();
// { selectAll: false, toggledRowIds: [1003, 1007] }
// or, after "select all" and two deselected rows:
// { selectAll: true, toggledRowIds: [1012, 1031] }
await fetch('/api/orders/bulk-archive', {
method: 'POST',
body: JSON.stringify({
selection,
// the query the user saw, so "every row" means the same rows on the server
query: hot.getPlugin('dataProvider').getQueryParameters(),
}),
});

Your server resolves the rows like this:

selectAllRows to act on
falseThe rows whose ids are in toggledRowIds.
trueEvery row matching the query, except the rows whose ids are in toggledRowIds.

To restore a saved selection, pass it to setServerSelection().

Count the selected rows

getSelectedCount() returns the number of selected rows, including the rows on other pages. After a “select all”, the count is the server’s totalRows minus the deselected rows.

The “select all” checkbox shows the same numbers in its accessible label, for example “Select all rows (24 of 40 selected)”.

Choose what “select all” selects

The server already filters the rows, so the 'all' and 'filtered' scopes of the selectAll option work the same way: they select every row that matches the current query.

To select only the rows on the current page, set selectAll to 'currentPage':

rowSelection: {
selectAll: 'currentPage',
},

The selection then lists each row id explicitly, and getServerSelection() always returns selectAll: false.

Known limitations

  • A “select all” means “every row matching the current query”. When the user changes the filters afterward, the selection follows the new query. Send the query with the selection, as in the example above.
  • The grid evaluates isRowSelectable only for the rows it loaded. After a “select all”, apply the same rule on your server.
  • After a “select all”, the count assumes every deselected row still matches the query.
  • The beforeRowSelectionChange and afterRowSelectionChange hooks list only the loaded rows whose state changes. Rows on other pages have no index to report.
  • After a “select all”, the Remove selected rows item of the context menu is disabled, because the grid can’t remove rows it never loaded. Send the selection to your server instead.

Configuration options

Hooks

Plugins