Skip to main content

Format data

Data is formatted using the data type setting in the schema. The data type is mapped to the grid.formatters object. In the following example col2 is data type date which will format data using the grid.formatters.date function. By default the string formatter is used to format all data. This method of formatting is faster than using the formattext event.

A formatter runs on every draw, including while a cell is being edited, so it must cope with values that are not (yet) valid for the type. Here an unparsable date is shown as-is instead of throwing.

import canvasDatagrid from 'canvas-datagrid';
import data from '/data.json';

const app = document.getElementById('app');
const gridElement = document.createElement('div');
const grid = canvasDatagrid({
  parentNode: gridElement,
  data,
  schema: [
    { name: 'col1' },
    {
      name: 'col2',
      type: 'date',
    },
    { name: 'col3' },
  ],
});

grid.formatters.date = function (e) {
  const date = new Date(e.cell.value);
  if (Number.isNaN(date.getTime())) {
    // not a date (yet): show the raw value rather than throwing
    return e.cell.value === undefined || e.cell.value === null
      ? ''
      : String(e.cell.value);
  }
  return date.toISOString();
};

app.append(gridElement);