Williams86
Williams86

Reputation: 321

How can I change color of text on basis of ifelse condition in R shiny?

I am trying with the below code.

library(shiny)

app <- shinyApp(
  ui = fluidPage(
    
    DT::dataTableOutput("mydatatable")
  ),
  
  
  server =  shinyServer(function(input, output, session) {
    
    mycars <- reactive({ head(mtcars)})
    output$mydatatable = DT::renderDataTable(mycars(), selection = 'single',  
                                             rownames = FALSE, options = list(dom = 't'))
    selected_row <- reactiveVal(value = NULL)
    observeEvent(input$mydatatable_rows_selected,{
      selected_row(input$mydatatable_rows_selected)
    })
    
    observeEvent(selected_row(),
                 {
                   showModal(modalDialog(
                     title = "You have selected a row!",
                     ifelse(
                       mycars()$mpg[selected_row()] > 21, 
                       tags$div(HTML(paste('cyl = ', tags$span(style = "color:red", mycars()$cyl[selected_row()]), sep = ""))),
                       tags$div(HTML(paste('cyl = ', tags$span(style = "color:blue", mycars()$cyl[selected_row()]), sep = "")))
                     )
                   ))
                 })
  })
)

app

Here I am trying to change color of 'cyl' value to red if 'mpg' value is greater than 21 else 'cyl' value will print in blue.

I have tried with few html codes but failed.

Thanks!

Upvotes: 0

Views: 518

Answers (1)

Lennyy
Lennyy

Reputation: 6132

For this purpose the dataframe does not have to be reactive, so I removed that part in here. Make use of the formatStyle functionality:

app <- shinyApp(
  ui = fluidPage(
    
    DT::dataTableOutput("mydatatable")
  ),
  
  
  server =  shinyServer(function(input, output, session) {
    
    mycars <- mtcars
    output$mydatatable = DT::renderDataTable(datatable(mycars) %>% 
                                               formatStyle('cyl', 'mpg',
                                                           color = styleInterval(21.001, c('blue', 'red'))),
                                                           selection = 'single',  
                                             rownames = FALSE, options = list(dom = 't'))
  })
)


app

Upvotes: 1

Related Questions