Skip to content

The same screen in React, Vue and Angular ​

This is the complete code for the same screen in React, Vue 3, Angular and JavaScript (a <script> tag). You can see side by side what changes from one framework to the next. Each piece of code was run against the built packages, so if you paste it into files it works as it is.

The screen behaves like this.

  • A 30-row table is shown, and clicking a row changes the line under the table.
  • Add row puts a new row at the top, and editing a value raises the change count.
  • Save sends all changes at once to a mock server (0.3 s delay). The server rejects rows whose name is Reject, so the save ends as a partial failure. Roll back cancels every unsaved change.
  • The sort, the number of selected rows and the focus position are shown under the table.
  • The Dark mode button switches the theme.
  • The Active column is drawn as a badge (a cell renderer), and editing the cell opens a select box (a cell editor). Both are cells made from framework components (Cells from components).

The tabs below are linked: choosing one anywhere switches every tab in the docs. For what all frameworks share, see the Framework guide.

Setup ​

In a React, Vue or Angular project, install the packages below (the shared data file uses types from @maxgrid/core) and load the theme CSS once at the app entry. The JavaScript tab needs no installation (one <script> line brings the CSS too).

bash
pnpm add @maxgrid/react @maxgrid/core @maxgrid/themes
ts
// At the top of main.tsx
import '@maxgrid/themes/grid.css';

Shared data ​

This file is used by all three frameworks. It always builds the same row from a number, and a mock server (mockSave) accepts the save. It rejects rows named Reject and sends back a new key for new rows.

sample.ts

ts
import type { ColumnDef, SaveHandler } from '@maxgrid/core';

export interface Employee {
  id: number;
  name: string;
  dept: string;
  salary: number;
  hiredAt: string;
  active: boolean;
}

const NAMES = [
  'Minjun Kim',
  'Seoyeon Lee',
  'Jiho Park',
  'Sua Choi',
  'Doyun Jung',
  'Haeun Kang',
  'Hyunwoo Cho',
  'Jiwoo Yoon',
];
const DEPTS = ['Dev', 'Design', 'Sales', 'HR', 'Ops'];

export function makeRow(id: number): Employee {
  const day = String((id % 28) + 1).padStart(2, '0');
  return {
    id,
    name: NAMES[id % NAMES.length],
    dept: DEPTS[id % DEPTS.length],
    salary: 3_000_000 + ((id * 137_000) % 4_000_000),
    hiredAt: `2024-${String((id % 12) + 1).padStart(2, '0')}-${day}`,
    active: id % 3 !== 0,
  };
}

export const rows: Employee[] = Array.from({ length: 30 }, (_, i) => makeRow(i + 1));

export const columns: ColumnDef<Employee>[] = [
  { id: 'id', title: 'No.', width: 70, align: 'end' },
  {
    id: 'name',
    title: 'Name',
    width: 110,
    editable: true,
    validation: { required: true, maxLength: 10 },
  },
  {
    id: 'dept',
    title: 'Dept',
    width: 110,
    kind: 'select',
    editable: true,
    editorOptions: DEPTS.map((value) => ({ value })),
  },
  {
    id: 'salary',
    title: 'Salary',
    kind: 'number',
    width: 130,
    editable: true,
    validation: { required: true, min: 0, max: 100_000_000 },
    formatValue: (value) => Number(value).toLocaleString('en-US'),
  },
  { id: 'hiredAt', title: 'Hired', kind: 'date', width: 120 },
  { id: 'active', title: 'Active', kind: 'boolean', width: 90, align: 'center', editable: true },
];

/** Mock server: answers after 0.3 s. Rejects rows named `Reject` and gives new rows a new key. */
export const mockSave: SaveHandler<Employee> = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  const failed = changes
    .filter((c) => c.state !== 'removed' && c.row.name === 'Reject')
    .map((c) => ({ key: c.key, message: 'The server rejected this name.' }));
  const ok = changes
    .filter((c) => c.state === 'added' && c.row.name !== 'Reject')
    .map((c) => ({ key: c.key, row: { ...c.row, id: Number(c.key) + 1000 } }));
  return { ok, failed };
};

export function describeSave(report: { status: string; committed: number; failed: number }) {
  if (report.status === 'saved') return `Saved (${report.committed})`;
  if (report.status === 'partial')
    return `Partly failed: ${report.committed} saved, ${report.failed} failed`;
  if (report.status === 'empty') return 'Nothing to save.';
  return 'Could not save.';
}

Employment badge and component editor ​

The cells of the Active column are made from framework components. The renderer receives the value and draws a badge, and the editor passes the value up through a select box. The editor only passes the value; confirming or cancelling with Enter, Esc and Tab is done by the grid's editing system.

cells.tsx

tsx
import type { CellEditorProps, CellRenderProps } from '@maxgrid/react';
import type { Employee } from './sample';

/** Cell renderer: draws the employment status as a badge. */
export function StatusBadge({ value }: CellRenderProps<Employee>) {
  return (
    <span className={value ? 'badge badge-on' : 'badge badge-off'}>
      {value ? 'Active' : 'On leave'}
    </span>
  );
}

/** Cell editor: passes the value up on choosing and asks to commit at once. */
export function StatusEditor({ value, error, onChange, commit }: CellEditorProps<Employee>) {
  return (
    <select
      defaultValue={value ? 'on' : 'off'}
      aria-invalid={error !== null}
      onChange={(event) => {
        onChange(event.target.value === 'on');
        commit();
      }}
    >
      <option value="on">Active</option>
      <option value="off">On leave</option>
    </select>
  );
}

The screen ​

One file (index.html). Open it in a browser. It needs no bundler and the data is inside the file. The Active badge is drawn by a cellRenderer adapter.

index.html

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>The same screen · JavaScript</title>
    <style>
      body {
        font-family: system-ui, sans-serif;
        margin: 16px;
      }
      .toolbar {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: center;
        margin: 12px 0;
      }
      #grid {
        height: 360px;
      }
      .badge {
        padding: 1px 8px;
        border-radius: 999px;
        font-size: 12px;
        background: #e5e7eb;
        color: #374151;
      }
      .badge-on {
        background: #d1fae5;
        color: #065f46;
      }
      [data-mxg-theme='dark'] body {
        background: #151a21;
        color: #e6e9ee;
      }
    </style>
  </head>
  <body>
    <h1>JavaScript demo</h1>
    <div class="toolbar">
      <button type="button" id="add">Add row</button>
      <button type="button" id="save">Save</button>
      <button type="button" id="rollback">Roll back</button>
      <button type="button" id="dark" aria-pressed="false">Dark mode</button>
      <button type="button" id="big">100,000 rows</button>
      <button type="button" id="toggle">Remove grid</button>
      <span id="changes">No changes</span>
      <span id="message">Click a row.</span>
    </div>
    <div id="grid"></div>
    <p id="status"></p>

    <script src="https://cdn.maxmine.com/maxgrid/1.8.0/maxgrid.min.js"></script>
    <script>
      var NAMES = [
        'Minjun Kim',
        'Seoyeon Lee',
        'Jiho Park',
        'Sua Choi',
        'Doyun Jung',
        'Haeun Kang',
        'Hyunwoo Cho',
        'Jiwoo Yoon',
      ];
      var DEPTS = ['Dev', 'Design', 'Sales', 'HR', 'Ops'];
      function makeRow(id) {
        var day = String((id % 28) + 1).padStart(2, '0');
        return {
          id: id,
          name: NAMES[id % NAMES.length],
          dept: DEPTS[id % DEPTS.length],
          salary: 3000000 + ((id * 137000) % 4000000),
          hiredAt: '2024-' + String((id % 12) + 1).padStart(2, '0') + '-' + day,
          active: id % 3 !== 0,
        };
      }
      function makeRows(count) {
        return Array.from({ length: count }, function (_, i) {
          return makeRow(i + 1);
        });
      }

      // Mock server: answers after 0.3 s. Rejects rows named `Reject` and gives new rows a new key.
      function mockSave(changes) {
        return new Promise(function (resolve) {
          setTimeout(resolve, 300);
        }).then(function () {
          return {
            failed: changes
              .filter(function (c) {
                return c.state !== 'removed' && c.row.name === 'Reject';
              })
              .map(function (c) {
                return { key: c.key, message: 'The server rejected this name.' };
              }),
            ok: changes
              .filter(function (c) {
                return c.state === 'added' && c.row.name !== 'Reject';
              })
              .map(function (c) {
                return { key: c.key, row: Object.assign({}, c.row, { id: Number(c.key) + 1000 }) };
              }),
          };
        });
      }

      var columns = [
        { id: 'id', title: 'No.', width: 70, align: 'end' },
        {
          id: 'name',
          title: 'Name',
          width: 110,
          editable: true,
          validation: { required: true, maxLength: 10 },
        },
        {
          id: 'dept',
          title: 'Dept',
          width: 110,
          kind: 'select',
          editable: true,
          editorOptions: DEPTS.map(function (value) {
            return { value: value };
          }),
        },
        {
          id: 'salary',
          title: 'Salary',
          kind: 'number',
          width: 130,
          editable: true,
          validation: { required: true, min: 0, max: 100000000 },
          formatValue: function (value) {
            return Number(value).toLocaleString('en-US');
          },
        },
        { id: 'hiredAt', title: 'Hired', kind: 'date', width: 120 },
        {
          id: 'active',
          title: 'Active',
          kind: 'boolean',
          width: 90,
          align: 'center',
          editable: true,
          // A cell renderer is a function that returns an adapter with mount, update and destroy.
          cellRenderer: function () {
            var badge;
            function paint(ctx) {
              badge.className = ctx.value ? 'badge badge-on' : 'badge';
              badge.textContent = ctx.value ? 'Active' : 'On leave';
            }
            return {
              mount: function (el, ctx) {
                badge = document.createElement('span');
                el.appendChild(badge);
                paint(ctx);
              },
              update: paint,
              destroy: function () {
                badge.remove();
              },
            };
          },
        },
      ];

      var container = document.getElementById('grid');
      var message = document.getElementById('message');
      var changes = document.getElementById('changes');
      var status = document.getElementById('status');
      var api = null;
      var sort = 'No sort';
      var selected = 0;
      var focus = 'No focus';
      function showStatus() {
        status.textContent = [sort, 'Selected ' + selected, focus].join(' · ');
      }

      function create() {
        api = MaxGrid.createGrid(container, {
          columns: columns,
          rows: makeRows(30),
          rowKey: 'id',
          ariaLabel: 'Employee table',
          showRowNumbers: true,
          selection: { mode: 'multiple', checkbox: true },
          saveMode: 'batch',
          saveHandler: mockSave,
        });
        api.on('cellClicked', function (e) {
          message.textContent = 'Last click: row ' + e.rowKey + ' / column ' + e.columnId;
        });
        api.on('sortChanged', function (e) {
          sort = e.sortModel.length
            ? 'Sort ' +
              e.sortModel
                .map(function (s) {
                  return s.columnId + ' ' + s.direction;
                })
                .join(', ')
            : 'No sort';
          showStatus();
        });
        api.on('selectionChanged', function (e) {
          selected = e.selectedKeys.length;
          showStatus();
        });
        api.on('focusChanged', function (e) {
          focus = e.rowKey === null ? 'No focus' : 'Focus ' + e.rowKey + '/' + e.columnId;
          showStatus();
        });
        api.on('changesCountChanged', function (e) {
          changes.textContent = e.count ? 'Changes: ' + e.count : 'No changes';
        });
        showStatus();
      }

      document.getElementById('add').onclick = function () {
        if (api) api.addRows([makeRow(api.getRowCount() + 1)], 0);
      };
      document.getElementById('save').onclick = function () {
        if (!api) return;
        api.save().then(function (r) {
          message.textContent =
            r.status === 'saved'
              ? 'Saved (' + r.committed + ')'
              : r.status === 'partial'
                ? 'Partly failed: ' + r.committed + ' saved, ' + r.failed + ' failed'
                : r.status === 'empty'
                  ? 'Nothing to save.'
                  : 'Could not save.';
        });
      };
      document.getElementById('rollback').onclick = function () {
        if (api) api.rollbackChanges();
      };
      document.getElementById('big').onclick = function () {
        if (api) api.setRows(makeRows(100000));
      };
      document.getElementById('dark').onclick = function (event) {
        var on = document.documentElement.getAttribute('data-mxg-theme') !== 'dark';
        if (on) document.documentElement.setAttribute('data-mxg-theme', 'dark');
        else document.documentElement.removeAttribute('data-mxg-theme');
        event.currentTarget.setAttribute('aria-pressed', String(on));
      };
      // You can clean up with destroy and create the grid again.
      document.getElementById('toggle').onclick = function (event) {
        if (api) {
          api.destroy();
          api = null;
          event.currentTarget.textContent = 'Recreate grid';
        } else {
          create();
          event.currentTarget.textContent = 'Remove grid';
        }
      };

      create();
    </script>
  </body>
</html>

The 100,000 rows button swaps the rows with setRows so you can check virtual scrolling. The files and their sizes are in Plain JavaScript.

Shared styles ​

The React, Vue and Angular tabs look the same with this one CSS file. Save it as src/styles.css. React and Vue import it in main, and Angular uses the file listed in styles of the angular.json above.

styles.css

css
.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin: 12px 0;
}
.badge {
  padding: 1px 8px;
  border-radius: 999px;
  font-size: 12px;
  background: #e5e7eb;
  color: #374151;
}
.badge-on {
  background: #d1fae5;
  color: #065f46;
}
[data-mxg-theme='dark'] {
  background: #151a21;
  color: #e6e9ee;
}

Inside a scaled container ​

When an ancestor has transform: scale(), pointer coordinates and getBoundingClientRect values are screen pixels, while inner lengths (offsetWidth and so on) are unscaled. Used as they are, column-resize drags and editor popups land in the wrong place. Give the grid the same factor in the scale option and it converts pointer, editor and toast coordinates to inner lengths.

ItemDescription
scaleA number (0.1 to 10, default 1) or 'auto'. 'auto' measures getBoundingClientRect().width / offsetWidth on every pointer press.
getScale()The factor in use, as a number (the measured value for 'auto').
setScale(n)Same as setOptions({ scale: n }). Accepts a number or 'auto'; anything else is invalid-option.
ts
const grid = createGrid(el, { columns, rows, rowKey: 'id', scale: 0.75 }); // parent is scale(0.75)
grid.setScale('auto'); // when the factor changes often
  • Without the option (default 1) nothing changes.
  • Menus and tooltips that open inside the grid with position: fixed (cell menu, column menu, filter menu, tooltip) are corrected for the scale: inside a transformed ancestor fixed is relative to that ancestor, so they are placed by measuring where they appear. Editor popups such as the combobox list open on the document (body) and use screen pixels as they are.

Where to go next ​