Search code examples
rshinybootstrap-5dtbslib

Is there a way to change color of specific DT lines when using bslib and bootstrap5?


I'm building an app using R shiny, bslib and DT.

With former version of bootstrap, it was simple to change the styling of the DT (including clolor of some line) using formatStyle function. But, for the new app, we use bslib and bootstrap 5 and the function seems broken, even if a user on github says it should be resolved (https://github.com/rstudio/DT/issues/1102). After some tests with different versions of DT and bslib (release and dev), I was still not able to make it work.

Is there another way to dynamically change the color of some composents of a DT with bslib and bootstrap 5?

library(bslib)
library(DT)

ui <- function(id) {
 card(
   DT::dataTableOutpu("repeatsTable")
}

server <- function(id) ({      
  output$repeatsTable <- DT::renderDataTable({
  repeatsDT <- DT::datatable(repeatsData(),
        extensions = c("Buttons", "ColReorder"),
        selection = "single",
        options = list(
          dom = "Bfrtip",
          buttons = list(I("colvis")),
          scrollX = TRUE,
          colReorder = TRUE
        )
      ) %>%
        formatStyle("isPathogenic", target = "row", color = styleEqual(c(0, 1, 2), c("black", "orange", "red")))
    })
})

edit: adding a dummy code of work (from link upper) that can run on itself

library(shiny)
library(dplyr)
library(DT)
library(bslib)

ui <- bslib::page_sidebar(
  DT::DTOutput("tab1")
)

server <- function(input, output) {
  output$tab1 <- DT::renderDT({
    mtcars %>% 
      head() %>% 
      # this line works
      #DT::datatable(style = "default") %>% 
      DT::datatable() %>% 
      DT::formatStyle(
        columns = "mpg", 
        target = "row", 
        color = DT::styleEqual(c(21), "white"),
        backgroundColor = DT::styleEqual(c(21), "#4d4d4d"),
      )
  })
}

shinyApp(ui = ui, server = server)

Solution

  • The problem is that the cells also have some CSS properties and they have priority over the CSS properties of the rows. A workaround is to unset the CSS properties of the cells:

      output$tab1 <- DT::renderDT({
        mtcars %>% 
          head() %>% 
          DT::datatable() %>% 
          DT::formatStyle(
            columns = 1:ncol(mtcars), 
            target = "cell", 
            color = JS("\"unset\""),
            backgroundColor = JS("\"unset\"")
          ) %>%
          DT::formatStyle(
            columns = "mpg", 
            target = "row", 
            color = DT::styleEqual(c(21), "white"),
            backgroundColor = DT::styleEqual(c(21), "orange")
          )
      })