Conditional row color depending on dropdown value

Tags: #<Tag:0x00007fa98e53b7b0>

I’m trying to set a classname for each cell in a row, depending on the value of a dropdown (when loading the grid and when changing the value). Here is the codesandbox: https://codesandbox.io/s/handsontable-demo-w4s9b

But I get an error: “TR was expected to be rendered but is not”, because when rendering the grid I cannot get the cell elements when calling getCell().

Is there any solution for this?

THX!

Hi @mirko

I think you can use beforeChange hook.
Here is a demo with this approach - https://codesandbox.io/s/handsontable-demo-4f59y

I finally added a modifyRowData handler to the handsontable settings:

hotSettings.modifyRowData = function(row) {
    const rowData = this.getSourceDataAtRow(row);

    if (rowData.approved !== null) {

      for (let i = 0; i < this.countCols(); i++) {
        const approved = rowData.approved === 'Yes';

        let colorClass = '';

        switch(rowData.approved) {
          case 'Yes':
            colorClass = 'bg-green';
            break;

          case 'No':
            colorClass = 'bg-red';
            break;

          default:
            break;
        }

        var meta = this.getCellMeta(row, i);
        
        meta.className = (meta.className + '').replace(/bg-green|bg-red/, '').trim();
        
        if (colorClass) {
          meta.className = meta.className + ` ${colorClass}`;
        }

        if (this.colToProp(i) !== 'approved') {
          meta.readOnly = approved;
        }
      }
    }
  }

Thank you for sharing the code. I’m sure it will help all those users who are looking for the same case.

1 Like