- Data Grid docs
- Start here
Recipes
Ready-to-copy solutions for common Data Grid tasks in JavaScript, React, Vue and Angular.
Common tasks, each complete enough to copy into an app. The feature pages explain the details.
Load from a REST API with infinite scroll
Your API pages with offset and limit and knows the total. The grid asks for 100 rows at a time as the user scrolls, and sends search, filters and sort along. See Remote data.
JavaScript
import { mountTable } from '@8sheets/data-grid';
const FIELDS = [
{ name: 'Order', type: 'number', format: '0' },
{ name: 'Customer', type: 'string' },
{ name: 'Revenue', type: 'number', format: '#,##0.00' },
];
const ordersSource = {
async query({ state, offset, limit, signal }) {
const params = new URLSearchParams({ offset, limit, q: state.search, sort: JSON.stringify(state.sort), filters: JSON.stringify(state.filters) });
const res = await fetch(`/api/orders?${params}`, { signal });
if (!res.ok) throw new Error(`Orders failed (HTTP ${res.status})`);
const { items, total, all } = await res.json();
return {
offset,
columns: FIELDS.map((f) => f.name),
rows: items.map((o) => ({ id: o.id, values: [String(o.id), o.customer, o.revenue.toFixed(2)], raw: [o.id, o.customer, o.revenue] })),
matches: total,
count: total,
sourceCount: all,
summary: '',
};
},
};
await mountTable(document.querySelector('#orders'), { title: 'Orders', fields: FIELDS, dataSource: ordersSource });React
import { useMemo } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';
import { ordersSource, FIELDS } from './orders-source.js'; // the source from the JavaScript tab
export function Orders() {
const options = useMemo(() => ({ title: 'Orders', fields: FIELDS, dataSource: ordersSource }), []);
return <div style={{ height: 600 }}><DataGrid options={options} /></div>;
}Vue
<script setup>
import { DataGrid } from '@8sheets/data-grid-vue';
import { ordersSource, FIELDS } from './orders-source.js'; // the source from the JavaScript tab
const options = { title: 'Orders', fields: FIELDS, dataSource: ordersSource };
</script>
<template>
<div style="height: 600px"><DataGrid :options="options" /></div>
</template>Angular
import { Component } from '@angular/core';
import { DataGridComponent, DataGridOptions } from '@8sheets/data-grid-angular';
import { ordersSource, FIELDS } from './orders-source'; // the source from the JavaScript tab
@Component({
selector: 'app-orders',
imports: [DataGridComponent],
template: `<eight-data-grid [options]="options" style="height: 600px" />`,
})
export class Orders {
options: DataGridOptions = { title: 'Orders', fields: FIELDS, dataSource: ordersSource };
}A master/detail order view
Orders in the grid; expanding one shows its lines, loaded when it opens. See Master/detail.
JavaScript
import { mountTable } from '@8sheets/data-grid';
function orderLines(record) {
const panel = document.createElement('div');
panel.textContent = 'Loading…';
fetch(`/api/orders/${encodeURIComponent(record.id)}/lines`)
.then((r) => r.json())
.then((lines) => {
const list = document.createElement('ul');
for (const l of lines) list.append(Object.assign(document.createElement('li'), { textContent: `${l.qty} × ${l.product}: ${l.amount.toFixed(2)}` }));
panel.replaceChildren(list);
})
.catch(() => (panel.textContent = 'The order lines could not be loaded.'));
return panel;
}
await mountTable(document.querySelector('#orders'), { title: 'Orders', data: orders, detailRenderer: orderLines });React
import { useMemo } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';
import { orderLines } from './order-lines.js'; // the function from the JavaScript tab
export function Orders({ orders }) {
const options = useMemo(() => ({ title: 'Orders', data: orders, detailRenderer: orderLines }), [orders]);
return <div style={{ height: 600 }}><DataGrid options={options} /></div>;
}Vue
<script setup>
import { computed } from 'vue';
import { DataGrid } from '@8sheets/data-grid-vue';
import { orderLines } from './order-lines.js';
const props = defineProps({ orders: Array });
const options = computed(() => ({ title: 'Orders', data: props.orders, detailRenderer: orderLines }));
</script>
<template>
<div style="height: 600px"><DataGrid :options="options" /></div>
</template>Angular
import { Component, Input } from '@angular/core';
import { DataGridComponent, DataGridOptions } from '@8sheets/data-grid-angular';
import { orderLines } from './order-lines';
@Component({
selector: 'app-orders',
imports: [DataGridComponent],
template: `<eight-data-grid [options]="options" style="height: 600px" />`,
})
export class Orders {
options: DataGridOptions = {};
@Input() set orders(data: Record<string, unknown>[]) {
this.options = { title: 'Orders', data, detailRenderer: orderLines };
}
}Export the selected rows
Tick records, then download them as an Excel file. See Row selection and Export.
JavaScript
const grid = await mountTable(document.querySelector('#orders'), { title: 'Orders', data: orders, rowSelection: 'multiple' });
document.querySelector('#export').onclick = () => grid.download('xlsx', { selected: true, fileName: 'selected-orders.xlsx' });React
// <DataGrid ref={ref} options={{ ...options, rowSelection: 'multiple' }} />
<button onClick={() => ref.current.download('xlsx', { selected: true, fileName: 'selected-orders.xlsx' })}>Export selected</button>Vue
<!-- <DataGrid ref="dataGrid" :options="{ ...options, rowSelection: 'multiple' }" /> -->
<button @click="dataGrid.download('xlsx', { selected: true, fileName: 'selected-orders.xlsx' })">Export selected</button>Angular
// template: <eight-data-grid #grid [options]="{ title: 'Orders', data: orders, rowSelection: 'multiple' }" />
// <button (click)="grid.download('xlsx', { selected: true, fileName: 'selected-orders.xlsx' })">Export selected</button>To send the file somewhere instead of saving it, exportResults('xlsx', { selected: true }) returns it as a Blob.
Show your own loading progress
The grid shows its own loading panel after 150 ms. To show progress in your app's own status bar as well, for example while a large CSV opens, use the load events; cancelLoad() stops it. See Loading large data.
JavaScript
const bar = document.querySelector('progress');
const label = document.querySelector('#load-label');
const grid = await mountTable(document.querySelector('#grid'), {
title: 'Imports',
onLoadStart: (e) => {
label.textContent = e.label; // "Opening sales.csv"
bar.hidden = false;
bar.removeAttribute('value'); // indeterminate until the size is known
},
onLoadProgress: (e) => {
if (e.fraction != null) bar.value = e.fraction;
},
onLoadEnd: (e) => {
bar.hidden = true;
label.textContent = e.status === 'done' ? `${e.records} records in ${(e.duration / 1000).toFixed(1)} s` : e.status === 'cancelled' ? 'Cancelled' : e.error.message;
},
});
document.querySelector('#cancel').onclick = () => grid.cancelLoad();
document.querySelector('#file').onchange = (e) => grid.openFile(e.target.files[0]).catch((err) => err.name === 'AbortError' || console.error(err));React
export function Imports() {
const ref = useRef(null);
const [load, setLoad] = useState(null);
return (
<>
{load && (
<p>
{load.label} <progress value={load.fraction ?? undefined} />
<button onClick={() => ref.current.cancelLoad()}>Cancel</button>
</p>
)}
<div style={{ height: 480 }}>
<DataGrid
ref={ref}
options={{ title: 'Imports' }}
onLoadStart={(e) => setLoad({ label: e.label, fraction: null })}
onLoadProgress={(e) => setLoad((l) => l && { ...l, fraction: e.fraction })}
onLoadEnd={() => setLoad(null)}
/>
</div>
</>
);
}Vue
<script setup>
import { ref } from 'vue';
import { DataGrid } from '@8sheets/data-grid-vue';
const dataGrid = ref(null);
const load = ref(null);
</script>
<template>
<p v-if="load">
{{ load.label }} <progress :value="load.fraction ?? undefined" />
<button @click="dataGrid.cancelLoad()">Cancel</button>
</p>
<div style="height: 480px">
<DataGrid
ref="dataGrid"
:options="{ title: 'Imports' }"
@load-start="(e) => (load = { label: e.label, fraction: null })"
@load-progress="(e) => load && (load.fraction = e.fraction)"
@load-end="load = null"
/>
</div>
</template>Angular
import { Component, ViewChild } from '@angular/core';
import { DataGridComponent } from '@8sheets/data-grid-angular';
@Component({
selector: 'app-imports',
imports: [DataGridComponent],
template: `
@if (label) {
<p>{{ label }} <progress [attr.value]="fraction" /> <button (click)="grid.cancelLoad()">Cancel</button></p>
}
<eight-data-grid #grid [options]="{ title: 'Imports' }"
(loadStart)="label = $event.label; fraction = null"
(loadProgress)="fraction = $event.fraction"
(loadEnd)="label = null"
style="height: 480px" />`,
})
export class Imports {
@ViewChild('grid') grid!: DataGridComponent;
label: string | null = null;
fraction: number | null = null;
}Save and restore a view
Keep each user's columns, filters, sort and groups on your server, and bring them back next time. See Sorting, grouping and views.
JavaScript
const grid = await mountTable(document.querySelector('#orders'), { title: 'Orders', data: orders });
const saved = await (await fetch('/api/me/views/orders')).json();
if (saved) await grid.setState(saved);
document.querySelector('#save-view').addEventListener('click', () =>
fetch('/api/me/views/orders', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(grid.getState()) }),
);React
<DataGrid
ref={ref}
options={options}
onReady={async (grid) => {
const saved = await (await fetch('/api/me/views/orders')).json();
if (saved) await grid.setState(saved);
}}
/>
// Save button:
fetch('/api/me/views/orders', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(ref.current.getState()) });Vue
<script setup>
import { DataGrid, useDataGrid } from '@8sheets/data-grid-vue';
defineProps({ options: Object });
const { dataGrid } = useDataGrid();
async function restore(grid) {
const saved = await (await fetch('/api/me/views/orders')).json();
if (saved) await grid.setState(saved);
}
const save = () =>
fetch('/api/me/views/orders', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(dataGrid.value.getState()) });
</script>
<template>
<button @click="save">Save view</button>
<div style="height: 480px"><DataGrid ref="dataGrid" :options="options" @ready="restore" /></div>
</template>Angular
// template: <button (click)="save()">Save view</button>
// <eight-data-grid #grid [options]="options" (ready)="restore($event)" />
@ViewChild('grid') grid!: DataGridComponent;
private http = inject(HttpClient);
restore(grid: MountedDataGrid) {
this.http.get<ReturnType<MountedDataGrid['getState']> | null>('/api/me/views/orders').subscribe((saved) => saved && grid.setState(saved));
}
save() {
this.http.put('/api/me/views/orders', this.grid.getState()).subscribe();
}Theme it to match your app
Use your brand colour for buttons, focus and selection, and follow your app's dark mode. See Themes.
JavaScript
const light = { base: 'light', tokens: { accent: '#7c3aed', 'on-accent': '#ffffff', panel: '#ffffff', 'panel-line': '#e5e7eb' } };
const dark = { base: 'dark', tokens: { accent: '#a78bfa', 'on-accent': '#1e1033' } };
const media = matchMedia('(prefers-color-scheme: dark)');
const grid = await mountTable(document.querySelector('#orders'), { data: orders, chrome: media.matches ? dark : light });
media.addEventListener('change', () => grid.setChrome(media.matches ? dark : light));React
// `chrome` changes in place: no remount.
const options = useMemo(() => ({ data: orders, chrome: isDark ? dark : light }), [orders, isDark]);
return <DataGrid options={options} />;Vue
// `chrome` changes in place: no remount.
const options = computed(() => ({ data: props.orders, chrome: isDark.value ? dark : light }));
// <DataGrid :options="options" />Angular
// A new options object that changes only `chrome` calls setChrome; the grid stays mounted.
@Input() set isDark(on: boolean) {
this.options = { ...this.options, chrome: on ? DARK : LIGHT };
}Validation in an editable grid
Required fields, a list of allowed values and a numeric range, checked as the user types; a rejected value keeps the editor open with your message. See Editing.
JavaScript
const fields = [
{ name: 'Order', type: 'number', format: '0', readOnly: true },
{ name: 'Customer', type: 'string', required: true },
{ name: 'Region', type: 'string', validator: { type: 'list', items: ['East', 'West', 'North', 'South'], message: 'Choose East, West, North or South.' } },
{ name: 'Units', type: 'number', required: true, validator: { type: 'whole', operator: 'between', min: 1, max: 500, message: 'Units must be a whole number from 1 to 500.' } },
{ name: 'Email', type: 'string', validator: { type: 'textLength', operator: 'lessThanOrEqual', value: 120, message: 'Keep the address under 120 characters.' } },
];
await mountTable(document.querySelector('#orders'), {
title: 'Order entry',
fields,
data: orders,
editable: true,
onChange: (change) => console.log('changed', change),
});React
// fields as in the JavaScript tab
const options = useMemo(() => ({ title: 'Order entry', fields, data: orders, editable: true }), [orders]);
return <DataGrid options={options} onChange={(change) => console.log('changed', change)} />;Vue
// fields as in the JavaScript tab
const options = computed(() => ({ title: 'Order entry', fields, data: props.orders, editable: true }));
// <DataGrid :options="options" @change="(change) => console.log('changed', change)" />Angular
// fields as in the JavaScript tab
options: DataGridOptions = { title: 'Order entry', fields: FIELDS, data: [], editable: true };
// template: <eight-data-grid [options]="options" (gridChange)="changed($event)" />
changed(change: DataGridChange) {
console.log('changed', change);
}Show an org chart as a tree
People with a manager ID, shown under their managers with salaries rolled up to each one, and an office picked from a list. See Tree data and Editing.
JavaScript
const fields = [
{ name: 'Id', type: 'number', format: '0', readOnly: true },
{ name: 'Manager', type: 'number', format: '0' },
{ name: 'Name', type: 'string', group: 'Person', required: true },
{ name: 'Role', type: 'string', group: 'Person', options: ['Director', 'Manager', 'Lead', 'Specialist'] },
{ name: 'Office', type: 'string', group: 'Work', options: ['Warsaw', 'Berlin', 'Paris'] },
{ name: 'Started', type: 'date', group: 'Work' },
{ name: 'Skills', type: 'string', editor: 'multiselect', options: ['Sales', 'Design', 'SQL', 'Support'] },
{ name: 'Salary', type: 'number', format: '#,##0' },
];
const grid = await mountTable(document.querySelector('#team'), { title: 'Company', fields, data: people, editable: true, rowNumbers: true });
await grid.setTree({ parent: 'Manager', key: 'Id', rollups: [{ field: 'Salary', agg: 'sum' }] });
await grid.setColumn('Id', { hidden: true });
await grid.setColumn('Manager', { hidden: true });React
// fields as in the JavaScript tab
const options = useMemo(() => ({ title: 'Company', fields, data: people, editable: true, rowNumbers: true }), [people]);
const showTree = async (grid) => {
await grid.setTree({ parent: 'Manager', key: 'Id', rollups: [{ field: 'Salary' }] });
await grid.setColumn('Id', { hidden: true });
await grid.setColumn('Manager', { hidden: true });
};
return <DataGrid options={options} onReady={showTree} />;Vue
// fields as in the JavaScript tab
const options = computed(() => ({ title: 'Company', fields, data: props.people, editable: true, rowNumbers: true }));
const showTree = (grid) => grid.setTree({ parent: 'Manager', key: 'Id', rollups: [{ field: 'Salary' }] });
// <DataGrid :options="options" @ready="showTree" />Angular
// fields as in the JavaScript tab
options: DataGridOptions = { title: 'Company', fields: FIELDS, data: [], editable: true, rowNumbers: true };
// template: <eight-data-grid [options]="options" (ready)="showTree($event)" />
showTree(grid: MountedDataGrid) {
grid.setTree({ parent: 'Manager', key: 'Id', rollups: [{ field: 'Salary' }] });
}Stream price updates
A feed that changes a few prices many times a second, applied in batches, with the changed cells flashing and a sparkline of the last months. See Live data.
JavaScript
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
const grid = await mountTable(document.querySelector('#prices'), {
title: 'Prices',
data: prices, // the record IDs are their positions in this array
flashChanges: true,
density: 'compact',
columnGroups: [{ caption: 'Volume, first half', fields: months }],
});
await grid.setColumn('Trend', { sparkline: { type: 'line', fields: months } });
const feed = new EventSource('/api/prices/stream');
feed.onmessage = (e) => {
const { id, price, change } = JSON.parse(e.data);
grid.applyTransactionAsync({ update: [{ id, values: { Price: price, Change: change } }] });
};React
// Pass `data` once; the feed goes through transactions so the view stays.
const options = useMemo(() => ({ title: 'Prices', data: prices, flashChanges: true, density: 'compact' }), []);
useEffect(() => {
const feed = new EventSource('/api/prices/stream');
feed.onmessage = (e) => {
const { id, price, change } = JSON.parse(e.data);
if (ref.current?.grid) ref.current.applyTransactionAsync({ update: [{ id, values: { Price: price, Change: change } }] });
};
return () => feed.close();
}, []);
return <DataGrid ref={ref} options={options} />;Vue
const options = { title: 'Prices', data: props.prices, flashChanges: true, density: 'compact' };
let feed;
onMounted(() => {
feed = new EventSource('/api/prices/stream');
feed.onmessage = (e) => {
const { id, price, change } = JSON.parse(e.data);
dataGrid.value.applyTransactionAsync({ update: [{ id, values: { Price: price, Change: change } }] });
};
});
onBeforeUnmount(() => feed?.close());
// <DataGrid ref="dataGrid" :options="options" />Angular
options: DataGridOptions = { title: 'Prices', data: PRICES, flashChanges: true, density: 'compact' };
private feed?: EventSource;
// template: <eight-data-grid #grid [options]="options" (ready)="start()" />
start() {
this.feed = new EventSource('/api/prices/stream');
this.feed.onmessage = (e) => {
const { id, price, change } = JSON.parse(e.data);
this.grid.applyTransactionAsync({ update: [{ id, values: { Price: price, Change: change } }] });
};
}
ngOnDestroy() {
this.feed?.close();
}Customize the context menu
Add your own command for the record under the pointer, and leave out the grid's export. See Context menu.
JavaScript
const grid = await mountTable(document.querySelector('#orders'), {
data: orders,
contextMenu: (items, { id, text }) => [
{ label: 'Email the customer', disabled: !text, action: () => openMail(id) },
{ separator: true },
...items.filter((item) => item.id !== 'export'),
],
});React
const options = useMemo(() => ({
data: orders,
contextMenu: (items, { id }) => [{ label: 'Email the customer', action: () => openMail(id) }, { separator: true }, ...items],
}), [orders]);
return <DataGrid options={options} />;Vue
const options = computed(() => ({
data: props.orders,
contextMenu: (items, { id }) => [{ label: 'Email the customer', action: () => openMail(id) }, { separator: true }, ...items],
}));
// <DataGrid :options="options" />Angular
options: DataGridOptions = {
data: ORDERS,
contextMenu: (items, { id }) => [{ label: 'Email the customer', action: () => this.openMail(id) }, { separator: true }, ...items],
};Ask for a view in words
The user writes "orders over 1,000 in the East, newest first"; your server asks a language model for a view state that matches the grid's schema, and the grid checks it before it applies. See Assistant.
JavaScript
async function askGridAssistant({ prompt, state, schema, language }) {
const res = await fetch('/api/grid-assistant', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, state, schema, language }),
});
return res.ok ? res.json() : { message: 'The assistant is unavailable right now.' };
}
const grid = await mountTable(document.querySelector('#orders'), { title: 'Orders', data: orders, assistant: askGridAssistant });React
// askGridAssistant as in the JavaScript tab
const options = useMemo(() => ({ title: 'Orders', data: orders, assistant: askGridAssistant }), [orders]);
return <DataGrid options={options} />;Vue
// askGridAssistant as in the JavaScript tab
const options = computed(() => ({ title: 'Orders', data: props.orders, assistant: askGridAssistant }));
// <DataGrid :options="options" />Angular
// askGridAssistant as in the JavaScript tab
options: DataGridOptions = { title: 'Orders', data: ORDERS, assistant: askGridAssistant };