Home  >  Q&A  >  body text

Possible problem: Unexpected results when using 'background-color' with 'DT'

As of version v0.26, the background-color of the DT package used in R shiny has changed. Is this the same problem for you and me? Is it a bug that changing the background color no longer works? !

library(shiny)

testUI <- function(id) {
  tagList(
    DT::dataTableOutput(NS(id, "mytable")),
    verbatimTextOutput(NS(id, "selected"))
  )
}

testServer <- function(id) {
  moduleServer(id, function(input,output,session,data) {
    output$mytable <- DT::renderDataTable({
      mtcars
    }, selection = list(mode = "multiple", target = "row"))

    output$selected <- renderPrint(
      input$mytable_rows_selected  # Caution: The prefix must match the id of my namespace
    )

  })
}

testApp <- function(install_version = c("v0.25", "v0.26"), change_background_color = FALSE) {

  stopifnot(is.logical(change_background_color))

  install_version <- match.arg(install_version)

  if (install_version == "v0.25") {
    remotes::install_github("rstudio/DT", ref = "v0.25", force = TRUE, upgrade = TRUE)
  } else {
    remotes::install_github("rstudio/DT", ref = "v0.26", force = TRUE, upgrade = TRUE)
  }

  ui <- fluidPage(

    if (isTRUE(change_background_color)) {
      tags$style(HTML('table.dataTable tr.selected td, table.dataTable td.selected {background-color: #FC8995 !important;}'))  # red color
    },

    testUI("test")
  )
  server <- function(input, output, session) {
    testServer("test")
  }
  shinyApp(ui, server)
}

DT version v0.25 without or with change background color:

testApp(install_version = "v0.25", change_background_color = FALSE)
testApp(install_version = "v0.25", change_background_color = TRUE)

DT version v0.26 Do not change background color and change background color:

testApp(install_version = "v0.26", change_background_color = FALSE)
testApp(install_version = "v0.26", change_background_color = TRUE)

Summary:

P粉983021177P粉983021177223 days ago441

reply all(1)I'll reply

  • P粉299174094

    P粉2991740942024-03-31 00:47:48

    The background color of the selected row in the new version is not set using the background-color property: it is set using the box-shadow property. Here's how to change the background color of selected rows:

    library(shiny)
    library(DT)
    
    css <- "
    table.dataTable tr.selected td, table.dataTable td.selected {
      box-shadow: inset 0 0 0 9999px #FC8995 !important;
    }
    "
    
    ui <- fluidPage(
      tags$style(HTML(css)),
      br(),
      DTOutput("dtable")
    )
    
    server <- function(input, output, session) {
      output[["dtable"]] <- renderDT({
        datatable(iris)
      })
    }
    
    shinyApp(ui, server)
    

    reply
    0
  • Cancelreply