ixodid
ixodid

Reputation: 2400

Programmatically change css in Shiny script

I wish to change the color of text in a Shiny app based on a user's input. Here's a simple example. Is this basically the correct approach? If I hard code the css it works. For example, if I change:

div(style = css_stub,

to

div(style = "inline-block;  red;",

the text color changes. Please explain how to alter css in a Shiny app programmatically.

library(shiny)

css_stub <- paste0("'", "inline-block;  color:black;", "'")

ui <- fluidPage(

  titlePanel("Color Test"),
  sidebarLayout(
    sidebarPanel(

      selectInput(inputId = "colors",
                  label = "Choose a color:",
                  choices = c("red", "blue"))
    ),

    mainPanel(
      div(style = css_stub, 
          textOutput("text_out"))

    )
  )
)

server <- function(input, output) {
  observeEvent(input$colors, {
    if (input$colors == "red") {
      css_stub <- paste0("'", "inline-block;  color:red;", "'")
      output$text_out <- renderText({"hello - red"})
    } else {
      css_stub <- paste0("'", "inline-block;  color:blue;", "'")
      output$text_out <- renderText({"hello - blue"})
    }
  })

}


shinyApp(ui = ui, server = server)

Upvotes: 2

Views: 2156

Answers (1)

Kota Mori
Kota Mori

Reputation: 6750

I would define classes and styles for each, then and add/remove classes using shinyjs library.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(), 
  tags$head(
    tags$style(HTML("
      div.red { color: red; }
      div.blue { color: blue; }
    "))
  ),

  titlePanel("Color Test"),
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "colors",
                  label = "Choose a color:",
                  choices = c("red", "blue"))
    ),

    mainPanel(
      div(id="color_change", style = "inline-block; ", 
          textOutput("text_out"))

    )
  )
)

server <- function(input, output) {
  observeEvent(input$colors, {
    color_to_set <- input$colors
    color_to_unset <- setdiff(c("red", "blue"), color_to_set)
    shinyjs::addClass("color_change", color_to_set)
    for (col in color_to_unset) shinyjs::removeClass("color_change", col)
  })

  output$text_out = renderText(paste("Hello -", input$colors))
}

shinyApp(ui = ui, server = server)

Upvotes: 5

Related Questions