Skip to content

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.

ts
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.

Live demo — drawn by the real renderer

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.

ts
{ 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.

ts
{
  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.

ts
{
  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.

ts
{
  id: 'salary',
  title: 'Salary',
  kind: 'number',
  cellClass: ({ value }) => (Number(value) >= 80_000 ? 'cell-high' : undefined),
}
css
.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.

ts
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,
});
tooltipOptionsDefaultMeaning
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)
followfalsetrue moves the tip with the pointer
hideDelay0ms to wait after leaving before hiding (0-2000)
hoverablefalsetrue 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). ctx has row, rowKey, columnId, text (the original text) and target ('cell' or 'header'); a returned function runs on hide. The column still needs tooltip or headerTooltip for a tip to appear. The original text also stays as the assistive description (aria-description). If it throws, the plain text is shown and an error event (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 Esc always closes it. Cell notes show before the column tooltip and work as before.
  • The tooltipShown and tooltipHidden events carry columnId, rowKey (null for headers), text and target ('cell', 'header' or 'note').

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.

ts
{
  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.005 with 2 decimals gives 1.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 (A is the AM/PM text of the locale). Other characters are printed as they are. Time tokens such as HH in a date column are printed literally.
  • stored is the shape of the string kept in the row data. Use YYYY, MM, DD, HH, mm, ss in 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: only YYYY and MM). Otherwise it is an invalid-option.
  • With stored the 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. updateRows writes the rows as given, so pass stored strings. A stored value that does not fit the shape reads as empty. setCellValue does not validate by default (use validate: 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) and formatDate(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.

ts
{ 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.

ts
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 as validation and dateTime are replaced whole, not merged.
  • columnDefaults and columnTypes cannot contain id, key or title. A type name missing from columnTypes is an invalid-option error.
  • defaultColumnWidth is the width of columns without width (40-1000, default 120).
  • The option editable: false makes every column read-only whatever the column says. Paste, clear and the edit keys are blocked too. true or omitted leaves it per column.
  • inferKind: true (column) picks the kind from the data when kind is omitted. If the first 50 non-empty values are all booleans it is boolean, numbers number, YYYY-MM-DD date, YYYY-MM-DD HH:mm datetime, HH:mm time, otherwise text. It is decided once when columns are set and not again when data changes. An explicit kind wins. A YYYY-MM string column becomes month; a mix of YYYY-MM-DD and YYYY-MM stays text.
  • autoColumns: { include?, exclude?, template? } builds columns from the keys of the first 20 rows when columns is an empty array and rows exist (kinds from inferKind, title is the key). No rows means no columns, and a non-empty columns always wins. Keys whose values are nested objects or arrays get no column because they cannot show as text (define them with a dotted key). inferKind treats impossible dates and times such as 2020-13-45 or 25:99 as text, 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 store null.
  • key accepts 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.

OptionWhereMeaning
rowStyleGridOptionsA style object, or (row, rowIndex) => object | null
rowClassRulesGridOptions{ className: (row, rowIndex) => boolean }. Every true class is added
rowTestIdGridOptions(row, rowKey) => string. Sets data-testid on the row (only when given)
cellStyleColumnA style object, or (ctx) => object | null (same ctx as cellClass)
cellClassRulesColumn{ className: (ctx) => boolean }
headerStyleColumnA fixed style object for the header cell
hoverGridOptions'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.

ts
{
  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.

ts
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> and reset.
  • Items have the same shape as cell menu items (id, label, run, disabled, separator). children are not a submenu in the column menu; they are placed flat right below the parent.
  • If the callback throws, it is reported as callback-error and 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 ​

PropertyDefaultDescription
idrequiredColumn identifier. Duplicate or empty values throw
keyidRow property to read the value from
titleidHeader text
kind'text'text, number, date, time, datetime, month, week, boolean, select, custom
widthfits the contentpx. When omitted, sized from the title and the first rows
minWidth, maxWidth–Lower and upper width bounds
alignend for number, otherwise start'start' | 'center' | 'end'
hiddenfalseHide the column
sortabletruefalse 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
mergeEmptyfalseWhen true, consecutive empty values merge into one cell too
mergeEditAllfalseWhen 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
filterabletruefalse excludes it from filter models
getValuerow[key]Compute the value
formatValueString(value), empty string for nullDisplay 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 formatValue returns is inserted as text. If you return <b>bold</b>, the tags are shown literally.
  • kind also accepts boolean, select and custom, but today they only change how values compare. Display and editing behave like text.
  • A duplicate column id throws duplicate-column-id; an empty one throws invalid-option. The codes are listed in Error handling.