- Data Grid docs
- Working with records
Sorting, grouping and views
Sort by several columns, group records into nested, collapsible groups with a summary, and save the whole view by name or in your own storage.
Sorting orders the records, grouping gathers them under a heading per value with a summary for each group, and a view is the whole arrangement (columns, search, filters, sort, groups) that you can save and restore. All of it is part of the grid's state, so your code can set it and keep it.
Open the sales example, grouped by region
In the grid
- Sort: click a heading to sort by it, again to reverse. Shift-click another heading to add it as the next sort key. The column menu has Sort ascending, Sort descending and Clear sort; the toolbar's Sort adds a key with its direction.
- Group: Group by in a column's menu or a cell's context menu, or the toolbar's Group. Each further field nests inside the previous one. A group's arrow collapses or expands it; sorting a grouped field also orders its groups.
- Tree: the Group dialog's Show as tree… shows each record under its parent instead of in groups; see Tree data.
- Summary: the toolbar's Summary picks one field and an aggregate (sum, average, minimum, maximum, count or distinct count). Each group shows it, and so does the footer for the whole result.
- Views: with a
storageKey(or a file opened in the grid), Views saves the current view under a name on this device, restores it, removes it, or resets the grid to its default view. - Selecting cells with the mouse or keyboard shows their count, sum and average in the footer.
From code
| State | Methods | Meaning |
|---|---|---|
sort: [{ field, desc }] | setSort, sortBy(field, { desc, add }), clearSort(field?) | Sort keys, first one first; add: true is Shift-click |
groups: [{ field, desc }] | setGroups, groupBy(field), clearGroups(field?) | Group fields, outermost first |
collapsed, collapseLevel | expandGroup(group), collapseGroup(group), expandAll(), collapseAll() | Which groups are closed. A group is named by its values from the top: ['East', 'Widget']. With a tree, expandAll() and collapseAll() open or close its branches |
total: { field, agg } | null | setSummary(summary) | The summary of each group and of the result |
getState() returns a copy of the whole view. setState(state) replaces it (keys left out take their defaults), updateState(patch) changes some keys, and resetState() goes back to every field in order with nothing filtered, sorted or grouped. Each change fires stateChange with the state and the keys that changed: the place to save a view as the user works.
collapseLevel starts groups closed: with collapseLevel: 1, every group below the top level starts collapsed, and collapsed then lists the ones the user opened.
Saved views
With a storageKey (or a file opened in the grid), saveView(name, state?), restoreView(name), deleteView(name) and getSavedViews() work on the same named views as the Views dialog, in the browser's local storage. To keep views elsewhere, such as per user on your server, save getState() and give it back to setState().
JavaScript
import { mountTable } from '@8sheets/data-grid';
const grid = await mountTable(document.querySelector('#orders'), {
title: 'Orders',
data: orders,
storageKey: 'orders',
// Keep the view as the user changes it.
onStateChange: (e) => localStorage.setItem('orders-view', JSON.stringify(e.state)),
});
const saved = localStorage.getItem('orders-view');
if (saved) await grid.setState(JSON.parse(saved));
else {
await grid.setGroups([{ field: 'Region' }, { field: 'Product' }]);
await grid.sortBy('Date', { desc: true });
await grid.setSummary({ field: 'Revenue', agg: 'sum' });
await grid.updateState({ collapseLevel: 1 }); // products start collapsed under each region
}
grid.saveView('By region'); // shows in the Views dialogReact
import { useRef } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';
export function Orders({ options, savedView, onSaveView }) {
const ref = useRef(null);
async function byRegion() {
await ref.current.setGroups([{ field: 'Region' }]);
await ref.current.setSummary({ field: 'Revenue', agg: 'sum' });
await ref.current.collapseAll();
}
return (
<>
<button onClick={byRegion}>By region</button>
<button onClick={() => ref.current.resetState()}>Reset</button>
<div style={{ height: 480 }}>
<DataGrid
ref={ref}
options={options}
onReady={(grid) => savedView && grid.setState(savedView)}
onStateChange={(e) => onSaveView(e.state)}
/>
</div>
</>
);
}Vue
<script setup>
import { ref } from 'vue';
import { DataGrid } from '@8sheets/data-grid-vue';
const props = defineProps({ options: Object, savedView: Object });
const emit = defineEmits(['save-view']);
const dataGrid = ref(null);
async function byRegion() {
await dataGrid.value.setGroups([{ field: 'Region' }]);
await dataGrid.value.setSummary({ field: 'Revenue', agg: 'sum' });
await dataGrid.value.collapseAll();
}
</script>
<template>
<button @click="byRegion">By region</button>
<button @click="dataGrid.resetState()">Reset</button>
<div style="height: 480px">
<DataGrid
ref="dataGrid"
:options="options"
@ready="(grid) => props.savedView && grid.setState(props.savedView)"
@state-change="(e) => emit('save-view', e.state)"
/>
</div>
</template>Angular
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { DataGridComponent, DataGridOptions, MountedDataGrid } from '@8sheets/data-grid-angular';
type View = ReturnType<MountedDataGrid['getState']>;
@Component({
selector: 'app-orders',
imports: [DataGridComponent],
template: `
<button (click)="byRegion()">By region</button>
<button (click)="grid.resetState()">Reset</button>
<eight-data-grid #grid [options]="options" (ready)="restore($event)" (stateChange)="saveView.emit($event.state)" style="height: 480px" />`,
})
export class Orders {
@Input() options: DataGridOptions = {};
@Input() savedView: View | null = null;
@Output() saveView = new EventEmitter<View>();
@ViewChild('grid') grid!: DataGridComponent;
restore(grid: MountedDataGrid) {
if (this.savedView) grid.setState(this.savedView);
}
async byRegion() {
await this.grid.setGroups([{ field: 'Region' }]);
await this.grid.setSummary({ field: 'Revenue', agg: 'sum' });
await this.grid.collapseAll();
}
}Limits
- Saved views from Views live in the browser's local storage, keyed by
storageKey, the title and the field names. UsegetStateto keep them anywhere else. - Grouping a server source sends
groupsto the server, which returns the group rows. - Groups and a tree don't combine: showing a tree clears the groups.