Search code examples
rshinynavbarbslib

Bslib change only navbar color


In my shiny app, I have an option allowing to change the theme app.
Is there a way to create a theme where only the navbar is colored and the body is black or white ?
I know it's possible to do it with CSS but as I could change the theme in the app it's not possible to do a custom fix.

enter image description here

library(shiny)
library(markdown)
library(bslib)

main_theme = bslib::bs_theme(
  bg = "#86cecb",
  fg = "#e12885",
  primary = "#89cff0",
)

ui = navbarPage(
  "Navbar!",
  theme = main_theme,
  tabPanel("Plot",
           sidebarLayout(
             sidebarPanel(radioButtons(
               "plotType", "Plot type",
               c("Scatter" = "p", "Line" = "l")
             )),
             mainPanel(plotOutput("plot"))
           )),
  navbarMenu(title = "Ressources",
             tabPanel(
               "Options d'interface",
               selectInput(
                 "theme",
                 "Themes :",
                 c(
                   "Custom" = "custom",
                   "Dark" = "dark",
                   "Light" = "light"
                 )
               )
             ))
)

server = function(input, output, session) {
  light <- bs_theme()
  
  dark <- bslib::bs_theme(
    bg = "#222222",
    fg = "#FFFFFF",
    primary = "#FFFFFF",
    secondary = "#434343"
  )
  main_theme = bslib::bs_theme(
    bg = "#86cecb",
    fg = "#e12885",
    primary = "#89cff0",
  )
  
  observe(session$setCurrentTheme({
    if (input$theme == "dark")
      dark
    else if (input$theme == "light")
      light
    else if (input$theme == "custom")
      main_theme
  }))
}

if (interactive())
  shinyApp(ui, server)

Solution

  • You could set the background color for the navbar individually using the Bootstrap variable navbar-bg:

    library(shiny)
    library(markdown)
    library(bslib)
    
    ui <- navbarPage(
      "Navbar!",
      theme = bslib::bs_theme(
        "navbar-bg" = "#86cecb",
        bg = "#222222",
        fg = "#e12885",
        primary = "#89cff0",
      ),
      tabPanel(
        "Plot",
        sidebarLayout(
          sidebarPanel(radioButtons(
            "plotType", "Plot type",
            c("Scatter" = "p", "Line" = "l")
          )),
          mainPanel(plotOutput("plot"))
        )
      ),
      navbarMenu(
        title = "Ressources",
        tabPanel(
          "Options d'interface",
          selectInput(
            "theme",
            "Themes :",
            c(
              "Custom" = "custom",
              "Dark" = "dark",
              "Light" = "light"
            )
          )
        )
      )
    )
    
    server <- function(input, output, session) {
      
    }
    
    shinyApp(ui, server)
    #> 
    #> Listening on http://127.0.0.1:5052