Search code examples
rconditional-formattingreactable

R Reactable highlight entire rows based on condition


I want to highlight all rows in a reactable 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(reactable)

mtcars %>% 
  reactable(striped = TRUE)

enter image description here

In this example, all rows where the cyl-value is 4 should be highlighted in yellow.

df_example <- mtcars %>% 
  mutate(backgorud_color = ifelse(cyl == 4 , "yellow", "grey"))

Can anyone help me with the configuration of the reactable?


Solution

  • Following the Conditional Styling vignette you can conditionally set the background color using a custom rendering function like so:

    library(tidyverse)
    library(reactable)
    
    mtcars %>%
      reactable(
        striped = TRUE,
        rowStyle = function(index) {
          if (mtcars[index, "cyl"] == 4) {
            list(background = "yellow")
          }
        }
      )
    

    enter image description here