Keeping the layout after a reload
stateKey saves column widths, order, hidden and pinned columns, sort and more in the browser and restores them on the next visit; reset columns is remembered and clearSavedState forgets it.
Live demoKeeping the layout
Change columns, reload the page: they stay.
Code for this demo
import { createGrid, type ColumnDef, type Row } from '@freegridjs/core';
import { makeRows } from '../data';
import { button, separator, text, tr, type DemoContext } from '../ui';
export default function mount(ctx: DemoContext) {
const h = (en: string, ko: string) => tr(ctx.lang, { en, ko });
const grid = createGrid(ctx.host, {
columns: [{ field: 'id', header: 'ID', type: 'number', width: 70 }, { field: 'name', header: h('Name', '이름'), width: 170 }, { field: 'company', header: h('Company', '회사'), width: 160 }, { field: 'country', header: h('Country', '국가'), width: 140 }, { field: 'q1', header: h('Q1', '1분기'), type: 'number', format: '#,##0', width: 120 }],
data: makeRows(500), locale: ctx.lang,
stateKey: 'docs-saved-layout',
});
for (const ev of ['columnResize', 'columnMove', 'columnVisible', 'sortChange'] as const) grid.on(ev, () => ctx.log(`${ev} → saved`));
text(ctx, h('Resize, move, hide (drag a header up) or sort, then reload the page: the layout comes back.',
'컬럼 너비·순서를 바꾸거나 숨기거나(헤더를 위로 끌기) 정렬한 뒤 페이지를 새로고침해 보세요. 그대로 돌아옵니다.'));
separator(ctx);
button(ctx, h('Reset columns', '컬럼 초기화'), () => grid.resetColumnState());
button(ctx, h('Forget the saved layout', '저장된 레이아웃 지우기'), () => { grid.clearSavedState(); ctx.log(h('cleared', '지웠습니다')); });
return grid;
}People widen, move, hide and pin columns and sort the rows. With a stateKey, the grid keeps that in the browser and restores it when the grid is made again — after a reload, a new tab or the next day.
createGrid(el, {
columns,
data,
stateKey: 'orders-grid', // one key per grid (and per page that shows it)
});Options and methods
| Name | Type | Description |
|---|---|---|
stateKey | string | The name to save under (stored as 'freegrid:state:<key>'). Give each grid its own. |
stateParts | SavedStatePart[] | What to keep. Default ['calculatedColumns', 'columns', 'columnGroups', 'sort']. |
stateStorage | 'local' | 'session' | localStorage (default: kept across visits) or sessionStorage (this tab only). |
resetColumnState() | void | Back to the column definitions: width, order, hidden, pinned. Saved too. The column menu's Reset columns does the same. |
clearSavedState() | void | Delete what was saved (the grid stays as it is until it is made again). |
What can be kept
| Part | Contains |
|---|---|
| 'columns' | Width, order, hidden and pinned state of each column |
| 'columnGroups' | Open or closed column groups |
| 'sort' | The sort |
| 'calculatedColumns' | Calculated columns people added |
| 'filters' · 'quickFilter' · 'advancedFilter' | Filters (careful: people may not notice rows are filtered) |
| 'groupBy' · 'expanded' · 'pivot' | Grouping, open groups, pivot |
| 'page' · 'pageSize' | The pager |
| 'notes' · 'selected' · 'conditionalFormats' | Cell notes, checked rows (needs getRowId), conditional formats |
When it saves and restores
- It saves a quarter of a second after a change (resize, move, hide, pin, sort, filter …), and at once when the page is left or the grid destroyed.
- It restores once, while the grid is created. Columns that no longer exist in your definitions are skipped; new columns appear where your definitions put them.
- A saved value that cannot be read (changed by hand) is ignored with a warning; the grid starts from the definitions.
- Blocked storage (private mode, full disk) only stops the saving; the grid works as usual.
Per person on your server
stateKey keeps the layout in one browser. To follow people across computers, save getState() on your server and give it back with setState():
const grid = createGrid(el, { columns, data });
grid.setState(await fetch('/api/me/grid-state').then(r => r.json()), { parts: ['columns', 'sort'] });
let timer;
const save = () => {
clearTimeout(timer);
timer = setTimeout(() => fetch('/api/me/grid-state', { method: 'PUT', body: JSON.stringify(grid.getState()) }), 500);
};
['columnResize', 'columnMove', 'columnVisible', 'sortChange'].forEach(ev => grid.on(ev, save));Questions about this page
How do I keep column widths and order after the page reloads?
Give the grid a stateKey such as 'orders-grid'. Widths, order, hidden and pinned columns and the sort are saved in localStorage as they change and come back the next time the grid is made.
How do I reset the saved column layout?
Reset columns in the column menu (or resetColumnState()) goes back to the column definitions and saves that. clearSavedState() deletes what was saved; the next visit starts from the definitions.