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. But not getting desirable output.

I have tried with few html codes but failed.

Thanks!

 observeEvent(selected_row(), {
      showModal(modalDialog(
        title = "You have selected a row!",
        tags$div(HTML(paste(
          "cyl = ",
          tags$span(mycars()$cyl[selected_row()],
            style = paste("color:", if (mycars()$mpg[selected_row()] > 21) {
              "red"
            } else {
              "blue"
            })
          )
        )))
      ))
    })
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.