How to highlight an entire row based on a condition?

28 Views Asked by At

I want to highlight all rows in a rhandsontable that meet a certain condition. Unfortunately, I have found neither an option nor a suggested solution for this on the net.

Here is my reproducible example:

library(tidyverse)
library(rhandsontable)

rhandsontable(mtcars) %>%
  hot_col(col = "cyl", renderer = "
  function (instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.NumericRenderer.apply(this, arguments);
    if ( value === 4 ) {
    td.style.background = '#ff000090';
    }
  }
  ")

In this example, all rows where the cyl-value is 4 should be highlighted in red.
My code already works for the respective cell:

enter image description here

However, I don't want the individual cell to be coloured red, but the entire row.
Can someone help me and make the adjustments in Javascript?

2

There are 2 best solutions below

1
Isaac On

Here is one solution, is not the most elegant, but it works. I had to place the cyl column in the last position to colour the full row, and identify the td that meet the condition.

rhandsontable(mtcars[, c(setdiff(names(mtcars), "cyl"), "cyl")]) %>%
  hot_col(col = "cyl", renderer = '
  function (instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.NumericRenderer.apply(this, arguments);
    if (value === 4) {
      $(td).parent().find("td").css("background-color", "#ff000090");
    }
  }
  ')

enter image description here

0
TobKel On

I found a solution based on this issue:
Color a whole row in rhandsontable based on a string value in one column

mtcars %>% 
  rhandsontable(
    row_highlight = which(.$cyl == 4) -1
  ) %>%
  hot_cols(renderer = "
            function (instance, td, row, col, prop, value, cellProperties) {
                     Handsontable.renderers.TextRenderer.apply(this, arguments);

                     if (instance.params) {
                       hrows = instance.params.row_highlight
                       hrows = hrows instanceof Array ? hrows : [hrows]
                       hcols = instance.params.col_highlight
                       hcols = hcols instanceof Array ? hcols : [hcols]

                       if (hrows.includes(row)) {
                         td.style.background = '#ff000090' 
                       }

                     }
            }"
  ) 

enter image description here