rconditional-formattingreactable

R Reactable add prefix to column based on condition


I have a dataframe with two columns: Condition & Value. Based on this dataframe I would like to create a reactable object. The Value column should have a prefix. It should be preceded by “Check” if the Condition column is TRUE. Unfortunately, I could not think of a solution to include a condition in the following code.

library(reactable)

df <- data.frame(
  Condition = c(TRUE, FALSE, TRUE, FALSE),
  Value = c(100, 200, 300, 400)
)

reactable(
  df,
  columns = list(
    Value = colDef(format = colFormat(prefix = "Check"))
  )
)

Here is the desired output:
enter image description here


Solution

  • You could use js for custom cell render:

    reactable::reactable(
      df,
      columns = list(
        Value = colDef(
          cell = reactable::JS("function(data) {
            if (data.row.Condition) {
              return 'Check ' + data.value;
            }
            return data.value;
          }")
        )
      )
    )