Columns
The full list of column options is in the API reference: ColumnDef and GridOptions.
Pass an array of ColumnDef to GridOptions.columns. For an employee list it looks like this.
import type { ColumnDef } from '@maxgrid/core';
interface Employee {
id: number;
name: string;
department: string;
salary: number;
joined: Date;
}
const columns: ColumnDef<Employee>[] = [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', key: 'department', title: 'Department' },
{ id: 'salary', title: 'Salary', kind: 'number' },
{ id: 'joined', title: 'Joined', kind: 'date' },
];id is required and must be unique across columns. If the column name differs from the property on your data, set key to the property, as dept does above. The wrapper packages (@maxgrid/react and so on) re-export the same types, so you can import from one package.
Fix widths and hide columns
width is in px and defaults to 120. Add minWidth and maxWidth to bound it. How users resize columns by dragging a header edge is in Column operations.
Use hidden: true for columns that must stay in the data but not on screen, such as memos or internal codes. A hidden column is not created in the DOM.
{ id: 'memo', title: 'Memo', hidden: true }Format money
formatValue builds the display string. The data keeps its original value, so sorting and filtering still work on numbers.
{
id: 'salary',
title: 'Salary',
kind: 'number',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
}kind: 'number' turns on right alignment and numeric comparison. kind: 'date' shows a Date as 2024-01-31.
Combine several fields
getValue computes the value from the row. Sorting and filtering use this value.
{
id: 'label',
title: 'Employee',
getValue: (row) => `${row.name} (${row.department})`,
}Highlight large values
The class returned by cellClass is added to the cell. Write the style in your app CSS.
{
id: 'salary',
title: 'Salary',
kind: 'number',
cellClass: ({ value }) => (Number(value) >= 80_000 ? 'cell-high' : undefined),
}.cell-high {
font-weight: 700;
}To style a whole row, use GridOptions.rowClass: (row, rowIndex) => string | undefined. Do not rely on color alone; add text or an icon so users who cannot see the color still get the information.
Per-row options and editors (editorOptions as a function, optionsFrom, optionLabel, cellEditorFor) are on Per-row options and editors.
Choose tooltips
The text of headerTooltip (headers) and tooltip (cells) shows as a tooltip. Every option below is optional and behavior is unchanged without them.
createGrid(el, {
tooltipOptions: {
placement: 'cursor',
follow: true,
hideDelay: 200,
hoverable: true,
trigger: 'both',
},
columns: [
{
id: 'price',
tooltip: (row) => String(row.price),
tooltipRenderer: (ctx, el) => {
const strong = document.createElement('strong');
strong.textContent = `${Number(ctx.text).toLocaleString()} KRW`;
el.append(strong); // return a function if there is something to clean up (called on hide)
},
},
],
rows,
});tooltipOptions | Default | Meaning |
|---|---|---|
placement | 'auto' | 'auto' goes below the target and flips above when there is no room. 'top' and 'bottom' never flip; 'cursor' goes near the pointer |
offset | { x: 0, y: 0 } | px added to the position (-200 to 200) |
follow | false | true moves the tip with the pointer |
hideDelay | 0 | ms to wait after leaving before hiding (0-2000) |
hoverable | false | true keeps the tip open while the pointer is on it (at least 150 ms grace after leaving) |
trigger | 'hover' | 'hover' is the mouse (touch press), 'focus' is keyboard focus on a cell or header, 'both' is both |
tooltipRenderer(ctx, el)fills the tip with DOM (never HTML strings).ctxhasrow,rowKey,columnId,text(the original text) andtarget('cell'or'header'); a returned function runs on hide. The column still needstooltiporheaderTooltipfor a tip to appear. The original text also stays as the assistive description (aria-description). If it throws, the plain text is shown and anerrorevent (callback-error) is emitted.- To tune only the tooltip of cell notes use
cellNoteOptions(Cell notes). - Only one tip is open at a time and
Escalways closes it. Cell notes show before the column tooltip and work as before. - The
tooltipShownandtooltipHiddenevents carrycolumnId,rowKey(nullfor headers),textandtarget('cell','header'or'note').
Gallery example: tooltip-options
Set the value format
Since 1.3.4
The column options format and parse are available from 1.3.4.
You can build display text with a formatValue function, but digits and date shapes can also be declared. Put them in the one column option format. When formatValue is set it wins.
{
id: 'price',
kind: 'number',
format: {
number: {
decimals: 2, // 0-10 decimal places
grouping: true, // thousands separator for the locale; a string uses that character
prefix: '$',
suffix: '',
rounding: 'round', // round (default, half away from zero) | floor | ceil | trunc
negative: 'parens', // minus (default) | parens: negatives as (1,234)
emptyText: '-', // shown when there is no value
},
},
},
{
id: 'due',
kind: 'date',
format: { date: { pattern: 'YYYY.MM.DD', stored: 'YYYYMMDD' } },
},- Rounding works on the shortest decimal form, so
1.005with 2 decimals gives1.01; binary float errors are not followed. A negative number that rounds to zero loses its sign. - Date pattern tokens are
YYYY YY MM M DD D HH H mm ss A(Ais the AM/PM text of the locale). Other characters are printed as they are. Time tokens such asHHin a date column are printed literally. storedis the shape of the string kept in the row data. UseYYYY,MM,DD,HH,mm,ssin this order with at most one separator character between tokens (YYYY.MM.DD,YYYYMMDDHHmmss). It must fit the column kind (date: the three date tokens,time: hour, minute[, second],datetime: both,month: onlyYYYYandMM). Otherwise it is aninvalid-option.- With
storedthe grid reads the standard value (2026-03-05) internally. The calendar, sort, filter, validation, paste and export all see the standard value; editing,setCellValue,fillColumn,updateCells, paste and undo write the stored shape.updateRowswrites the rows as given, so pass stored strings. A stored value that does not fit the shape reads as empty.setCellValuedoes not validate by default (usevalidate: true), so text that is not a date goes into the row as it is and reads as empty; give stored-format columns standard date values. - The same functions are available as
formatNumber(value, format, locale)andformatDate(value, pattern, locale).
To turn typed text into a value use parse. If parse(raw, row) returns a value it is used; if it throws or returns undefined the input is refused with "the value is not valid". It applies to typing and paste and is not called for blank text. The commit order is editor -> parse -> hooks.transformEdit -> validation -> store.
{ id: 'won', kind: 'number', editable: true, parse: (raw) => Number(raw.replace(/[,\s]/g, '')) || undefined }The same number format object can be given to aggregateFormat (aggregateFormat: { decimals: 0, grouping: true, suffix: ' USD' }). The value written when a date is cleared with the calendar's Clear button is set with dateTime.clearValue (a text such as 'TBD' skips date validation and is written as it is).
Defaults and column types
Put shared settings in options instead of repeating them on every column. With none of these options set, behavior is unchanged.
createGrid(el, {
columnDefaults: { align: 'center', editable: true },
columnTypes: { money: { kind: 'number', align: 'end', width: 110 } },
defaultColumnWidth: 110,
columns: [
{ id: 'name' },
{ id: 'price', type: 'money' },
{ id: 'note', width: 220, align: 'start' },
],
rows,
});- Merge order:
columnDefaults<columnTypes[type](an array of names applies left to right) < the column's own definition. Each property is replaced shallowly, so nested objects such asvalidationanddateTimeare replaced whole, not merged. columnDefaultsandcolumnTypescannot containid,keyortitle. Atypename missing fromcolumnTypesis aninvalid-optionerror.defaultColumnWidthis the width of columns withoutwidth(40-1000, default 120).- The option
editable: falsemakes every column read-only whatever the column says. Paste, clear and the edit keys are blocked too.trueor omitted leaves it per column. inferKind: true(column) picks the kind from the data whenkindis omitted. If the first 50 non-empty values are all booleans it isboolean, numbersnumber,YYYY-MM-DDdate,YYYY-MM-DD HH:mmdatetime,HH:mmtime, otherwisetext. It is decided once when columns are set and not again when data changes. An explicitkindwins. AYYYY-MMstring column becomesmonth; a mix ofYYYY-MM-DDandYYYY-MMstaystext.autoColumns: { include?, exclude?, template? }builds columns from the keys of the first 20 rows whencolumnsis an empty array and rows exist (kinds frominferKind, title is the key). No rows means no columns, and a non-emptycolumnsalways wins. Keys whose values are nested objects or arrays get no column because they cannot show as text (define them with a dottedkey).inferKindtreats impossible dates and times such as2020-13-45or25:99astext, not date or time.emptyAs: 'null' | 'empty'(column) sets what an empty input stores on edit, paste and clear. Text columns default to''; number, date and time columns always storenull.keyaccepts a dotted path such as'address.city'. Reading, sorting, filtering, editing, pasting and export all follow it. Writing copies the objects along the path, so the original row's nested objects are not changed. A property literally named'address.city'on the row wins.
Examples: column-defaults, column-types and auto-columns in the gallery.
Conditional styles and hover range
These options change the look by value. All are optional; without them the grid is drawn exactly as in 1.3.2.
| Option | Where | Meaning |
|---|---|---|
rowStyle | GridOptions | A style object, or (row, rowIndex) => object | null |
rowClassRules | GridOptions | { className: (row, rowIndex) => boolean }. Every true class is added |
rowTestId | GridOptions | (row, rowKey) => string. Sets data-testid on the row (only when given) |
cellStyle | Column | A style object, or (ctx) => object | null (same ctx as cellClass) |
cellClassRules | Column | { className: (ctx) => boolean } |
headerStyle | Column | A fixed style object for the header cell |
hover | GridOptions | 'row' (default), 'cell', 'column', 'cross' (row + column), 'none' |
Style names are camelCase (backgroundColor) or --custom variables, and values are strings or numbers only. A name that is missing on the next draw is cleared. Row position and height (position, top, left, transform, height) and cell placement (gridColumn, gridRow, display) belong to the grid and cannot be changed. Class names must be safe tokens without spaces. If a callback throws, an error event (callback-error) is reported and that row or cell is drawn unstyled.
{
rowStyle: (row) => (row.stock <= 5 ? { backgroundColor: 'rgba(255, 200, 0, .18)' } : null),
rowClassRules: { soldout: (row) => row.stock === 0 },
rowTestId: (row, key) => `item-${key}`,
hover: 'cross',
}hover: 'column' adds the class mxg-col-hover to the cells of the hovered column (also to rows drawn later while scrolling). It does nothing on touch screens. Do not rely on color alone; add text or an icon too.
Conditional styles example · Column hover example
Change the column menu items
Give columnMenu an object to change the menu items (1.3.6). It turns the menu on, like true.
columnMenu: {
items: (defaults, { columnId, column, api }) => [
...defaults.filter((item) => item.id !== 'reset'),
{ id: 'sep-mine', label: '', separator: true },
{ id: 'mine', label: `Hide ${column.title}`, run: () => api.setColumnVisible(columnId, false) },
],
header: true, // also open on header right-click (default). false: button only, right-click shows the browser menu
},- Default item ids are
sort-asc,sort-desc,sort-clear,autofit,pin-start,pin-end,unpin,hide,col:<column id>andreset. - Items have the same shape as cell menu items (
id,label,run,disabled,separator).childrenare not a submenu in the column menu; they are placed flat right below the parent. - If the callback throws, it is reported as
callback-errorand the default items show.
Sort on the server
With sortMode: 'server', a header click or setSortModel only reports sortChanged and does not sort rows. Your app receives sortChanged and puts the sorted data back in. With server paging the same model travels in the sort of the loadPage request. The default 'client' is as before.
Change columns at runtime
Replace them with api.setColumns(columns) or setOptions({ columns }), and columnsChanged fires. With a wrapper, assign a new array to options.columns. If a sort or filter model refers to a column that disappears, that entry is dropped.
Add a row-number column at the start with showRowNumbers: true.
Options
| Property | Default | Description |
|---|---|---|
id | required | Column identifier. Duplicate or empty values throw |
key | id | Row property to read the value from |
title | id | Header text |
kind | 'text' | text, number, date, time, datetime, month, week, boolean, select, custom |
width | fits the content | px. When omitted, sized from the title and the first rows |
minWidth, maxWidth | – | Lower and upper width bounds |
align | end for number, otherwise start | 'start' | 'center' | 'end' |
hidden | false | Hide the column |
sortable | true | false excludes it from header-click sorting and sort models |
merge | – | Cells that repeat down the column become one. 'top' shows the value on the first row only. Empty values, group rows and cellRenderer columns are not merged |
mergeWithin | – | Use with merge. The merge breaks where the given columns (an id, a list, or true for every merged column before this one) change |
mergeLabel | 'start' | Where the value shows. With merge: 'top' it is the first row (default) or 'center' for the middle row of the visible span; with merge: true, 'start' puts it at the first row of the merged cell |
mergeEmpty | false | When true, consecutive empty values merge into one cell too |
mergeEditAll | false | When true, editing a merged cell (cell edit mode) writes the value to every row of the group, and undo reverts them together |
mergeCols | – | Set on the first column of a horizontal merge (an integer of 2 or more). Within that many columns to the right, neighbouring equal values in the same row become one cell. It does not cross a pinned area. It can be combined with merge, and a row merged across is left out of the vertical merge |
mergeColsWhen | – | (row, rowIndex) => boolean. A row for which it returns false is not merged across |
filterable | true | false excludes it from filter models |
getValue | row[key] | Compute the value |
formatValue | String(value), empty string for null | Display string |
cellClass | – | A string or (ctx) => string | undefined |
Wrapping columns
wrap: true wraps cell text (by word for Korean) and wrapHeader: true wraps the header title. For rows to grow with their content add rowHeight: 'auto', and for the header headerHeight: 'auto'. See Wrapping columns and headers.
Multi-line body
To draw one row on several lines with bodyLayout and bandSpan, see Draw one row on several lines.
Things that trip people up
- The string
formatValuereturns is inserted as text. If you return<b>bold</b>, the tags are shown literally. kindalso acceptsboolean,selectandcustom, but today they only change how values compare. Display and editing behave liketext.- A duplicate column
idthrowsduplicate-column-id; an empty one throwsinvalid-option. The codes are listed in Error handling.