Handsontable example

by handsoncode

HTML

<p>
  This example is made to add column at the end of the table while using object source data
</p>
<div id="example"></div>
<script src="https://cdn.jsdelivr.net/npm/handsontable@latest/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable@latest/dist/handsontable.full.min.css">

Babel + JSX

const cols = [
  {
    data: 'id'
  }, {
    data: 'name'
  }, {
    data: 'age'
  }
];
const example = document.getElementById('example');
const hot = new Handsontable(example, {
  data: [
    {
      id: 1,
      name: 'John',
      age: 20
    }
  ],
  licenseKey: 'non-commercial-and-evaluation',
  columns: cols,
  rowHeaders: true,
  colHeaders: true,
  contextMenu: {
    items: {
      "custom_item": { // type anything that is not already predefined by Handsontable
        name: 'Add one additional column', // add your custom label
        callback(key, options) { //this is the part where you attach your custom code
          cols.push({ data: 'email' }); // add another key to the columns

          this.updateSettings({ // let Handsontable know that the pattern changed
            columns: cols
          });

          this.setDataAtRowProp(0, 'email', '[email protected]') //here I use the new key to attach data
        }
      }
    }
  }
});