JSFiddle - React, Tailwind, and code Playground

by handsoncode

HTML

<script src="https://cdn.jsdelivr.net/npm/handsontable@13.0/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable@13.0/dist/handsontable.full.min.css" /> 

<div id="example"></div>

JavaScript

const OPTIONS = new Map([
  ['2020', () => ['Jack', 'Bob', 'Same']],
  ['2021', () => ['WW', 'Saddy', 'Caven']],
  ['2022', () => ['VC', 'Pob', 'DJ']],
]);

const getChilds = (year) => {
  switch (year) {
    case '2020':
      return ['Jack', 'Bob', 'Same'];
    case '2021':
      return ['WW', 'Saddy', 'Caven'];
    case '2022':
      return ['VC', 'Pob', 'DJ'];
    default:
      return [];
  }
}

const data = [{
    year: '2020',
    owner: 'Jack'
  },
  {
    year: '2021',
    owner: 'WW',
  },
  {
    year: '2022',
    owner: 'VC',
  }
]

const columns = [{
    data: 'year',
    title: 'Year',
    type: 'dropdown',
    source: ['2020', '2021', '2022'],
    readOnly: false,
    width: 115,
  },
  {
    data: 'owner',
    title: 'Owner',
    type: 'dropdown',
    source: [],
    readOnly: false,
    width: 115,
  },
]

const container = document.getElementById('example');

let hot = new Handsontable(container, {
  licenseKey: 'non-commercial-and-evaluation',
  data: [],
  colWidths: 60,
  columns: columns,
  rowHeaders: true,
  colHeaders: true,
  afterLoadData: function(sourceData, initialLoad, source) {
    if (source === 'onLoadData') {
      sourceData.forEach((row, index) => {
        const listOfChilds = getChilds(row.year);
        this.setCellMeta(
          index,
          this.propToCol('owner'),
          'source',
          listOfChilds,
        );
      })
    }
  },
  afterChange: (changes, source) => {
    if (source === 'loadData' || source === 'internal' || changes.length > 1) {
      return;
    }

    const [row, prop, oldValue, newValue] = changes[0];

    if (prop !== 'year') {
      return;
    }
    if (!OPTIONS.has(newValue)) {
      return;
    }

    const option = OPTIONS.get(newValue)();

    hot.setCellMeta(row, hot.propToCol('owner'), 'source', option);
    hot.setDataAtRowProp(row, 'owner', option[0]);
  },
});


hot.loadData(data, 'onLoadData')
hot.render()