Search code examples
rbootstrap-5dtbslib

Override DT style when using bslib (Bootstrap 5)


I am using both bslib and DT to create a shiny app and I would like to change the header color of some datatables. I found thoss questions regarding the issue :

The answer to the 1st question works perfectly fine for Bootstrap 4, but not for Bootstrap 5. The answer to the 2nd question found a workaround for the cells style using "unset" with formatStyle, but I didn't manage to replicate it with the initComplete argument that normally allows to change a DT's style without bslib (mentionned in the answer to the 3rd question)

Is there a way to modify the style of a DT when using bslib with Bootsrap 5 ?

Here is a reproducible exemple :

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


ui <- page_fluid(
  theme = bs_theme(
    # version = 4
    version = 5
  ) 
  %>% bs_add_rules(
    as_sass("table.dataTable thead { background: red !important; }")
  ),
  dataTableOutput("dummyDT")
)

server <- function(input, output, session){
  output$dummyDT <- renderDataTable({
    datatable(mtcars)
  })
  
  session$onSessionEnded(function() {stopApp()})
}


shinyApp(ui, server)

Solution

  • You could get more specific with your css and apply the red background to the thead row headers:

    library(dplyr)
    library(shiny)
    library(DT)
    library(bslib)
    library(sass)
    
    ui <- page_fluid(
      theme = bs_theme(version = 5) 
      %>% bs_add_rules(as_sass("table.dataTable thead tr th { background: red }")),
      dataTableOutput("dummyDT")
    )
    
    server <- function(input, output, session){
      output$dummyDT <- renderDataTable({
        datatable(mtcars)
      })
    }
    
    shinyApp(ui, server)
    

    enter image description here