Reputation: 11140
I am using DT::renderDT
in a shiny app and am formatting background color for certain columns and rows. I need the row background color to be on top of column background color. I tried switching order of formatStyle
but that didn't work. Here's a small example -
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
DTOutput("table")
),
server = function(input, output, session) {
output$table <- renderDT({
head(iris) %>%
datatable() %>%
formatStyle(c(2,4), backgroundColor = "#fcf4d9") %>%
formatStyle(1, target = 'row',
backgroundColor = styleEqual(c(4.7, 5), c("#fc8a8a", "#fc8a8a"))
# comment above row and ucomment below row for row color using styleInterval()
# backgroundColor = styleInterval(c(0, 5, 9), c('blue', 'green', 'red', 'orange'))
)
})
}
)
Result (incorrect) with styleEqual()
-
Result (incorrect) with StyleInterval()
-
The row colors need to be on top of yellow (column color).
Looking for a generalized solution that would work for multiple rows and with styleEqual()
or styleInterval()
. Any help is appreciated. Thanks!
Upvotes: 1
Views: 1972
Reputation: 84529
Here is a solution:
rowCallback <- c(
"function(row, data, displayNum, displayIndex, dataIndex){",
" if(data[1] === 4.7){",
" $(row).find('td').addClass('red');",
" }",
"}"
)
shinyApp(
ui = fluidPage(
tags$head(
tags$style(
HTML(
"table.dataTable tbody tr td.red {background-color: #fc8a8a !important}"
)
)
),
DTOutput("table")
),
server = function(input, output, session) {
output$table <- renderDT({
head(iris) %>%
datatable(options = list(rowCallback = JS(rowCallback))) %>%
formatStyle(c(2,4), backgroundColor = "#fcf4d9")
})
}
)
Upvotes: 2