Use bslib to customize the CSS of DT::datatable in Shiny applications
P粉081360775
P粉081360775 2024-03-29 21:41:03
0
1
419

I'm trying to apply custom CSS styles to a DT::datatable in a shiny application. When the user selects a row in the table, I want the selected row to have yellow, black text instead of the default blue, white text. I cannot do this successfully when I also use the bslib package.

(A similar question was asked here, but I can't answer it, as I'll describe below).

Without bslib, I can successfully apply the css like this:

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style(
      HTML("table.dataTable tbody tr.selected td {
             color: black !important;
             box-shadow: inset 0 0 0 9999px yellow !important;}"
      )
    )
  ),
  DT::dataTableOutput("test_table")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
    DT::datatable(iris, selection = 'single')
  })
}

shinyApp(ui, server = server)

Successful CSS

However, I found that using the bslib theme, I couldn't apply the css using the same method.

I've seen these two resources point to using the bslib::bs_add_rules function to solve this problem:

  • https://github.com/rstudio/bslib/issues/360
  • Override DT default color selection when using bslib

Based on these, I tried the following variations but can't seem to get it to work:

library(shiny)

ui <- bslib::page_fluid(
  theme = bslib::bs_add_rules(
      bslib::bs_theme(),
      sass::as_sass("table.dataTable tbody tr.selected td {
             color: black !important;
             box-shadow: inset 0 0 0 9999px yellow !important;}"
      )),
  DT::dataTableOutput("test_table")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
      DT::datatable(iris, selection = 'single')
  })
}

shinyApp(ui, server = server)

Unsuccessful CSS

P粉081360775
P粉081360775

reply all(1)
P粉722409996

The problem is with the object tag. If you check the HTML code, you'll see that when you use sass::as_sass it should be .table.dataTable tbody tr.active td , not table. dataTable tbody tr.selected td

library(shiny)

ui <- bslib::page_fluid(
  theme = bslib::bs_add_rules(
    bslib::bs_theme(),
    sass::as_sass("table.dataTable tbody tr.active td {
             color: black !important;
             box-shadow: inset 0 0 0 9999px yellow !important;}"
    )),
  DT::dataTableOutput("test_table")
)

server <- function(input, output, session) {
  
  output$test_table <- DT::renderDataTable({
    DT::datatable(iris, selection = 'single')
  })
}

shinyApp(ui, server = server)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template