Home > Software engineering >  Change the header colour of a shinydashboard app reactively
Change the header colour of a shinydashboard app reactively

Time:07-07

I have a shinydashboard application. I want to have two radio buttons - say labelled "green" and "red" and for the header/navbar to change colour to either green or red to reflect the users selection. Is this possible?

I know you can use CSS to make the header/navbar a different colour and there are some packages (like fresh) that can a similar thing, but I don't know any way of changing it reactively.

Thanks!

Edit: my code is here. All the elements that are currently coloured #D55E00 I would like to change colour when the button is switched

library(shinydashboard)
library(shiny)

ui <- dashboardPage(
  dashboardHeader(title="Title"),
  dashboardSidebar(
    radioButtons(
      inputId = "colourswitch",
      label = "Click here!",
      choices = c("red", "green")
    )
    
  ),
 dashboardBody(
    tags$head(tags$style(HTML('
      /* logo */
      .skin-blue .main-header .logo {background-color: #D55E00;}

      /* logo when hovered */
      .skin-blue .main-header .logo:hover {background-color: #D55E00;}

      /* toggle button when hovered  */
        .skin-blue .main-header .navbar .sidebar-toggle:hover{background-color: #D55E00;}

      /* navbar (rest of the header) */
      .skin-blue .main-header .navbar {background-color: #D55E00;}'))),
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

CodePudding user response:

Here is a cheap way to change the color from server without using any Javascript, purely with CSS.

library(shinydashboard)
library(shiny)
library(glue)

ui <- dashboardPage(
    dashboardHeader(title="Title"),
    dashboardSidebar(
        radioButtons(
            inputId = "colourswitch",
            label = "Click here!",
            choices = c("orange"="#D55E00","red"="red", "green"="green")
        )
        
    ),
    dashboardBody(
        uiOutput("navcolor"),
        tags$head(tags$style(HTML('
      /* logo */
      .skin-blue .main-header .logo {background-color: var(--nav-color);}

      /* logo when hovered */
      .skin-blue .main-header .logo:hover {background-color: var(--nav-color);}

      /* toggle button when hovered  */
        .skin-blue .main-header .navbar .sidebar-toggle:hover{background-color: var(--nav-color);}

      /* navbar (rest of the header) */
      .skin-blue .main-header .navbar {background-color: var(--nav-color);}'))),
    )
)

server <- function(input, output, session) {
    output$navcolor <- renderUI({
        tags$style(HTML(glue(
            "
            :root {
                --nav-color: @{input$colourswitch}@
            }
            ",
            .open = "@{", .close = "}@"
        )))
    })
}

shinyApp(ui, server)

enter image description here

  • Related