htmlrshinybootstrap-5bslib

How to Style navigable page sidebar in Shiny using bslib


I'm trying to style my Shiny app page using bslib and wanted to make the sidebar similar to like this in bootstrap examples but don't know how to implement the similarly in shiny using bslib.

Question : How to create these kind of bootstrap sidebar, is there a direct function like sidebar(). After implementation of the bootstrap sidebar how can on click open different page in the main panel.

Sample R script :

library(bslib)
library(shiny)
library(ggplot2)
  
ui <- page_sidebar(
  title = "Example dashboard",
  sidebar = sidebar(
    varSelectInput("var", "Select variable", mtcars)
  ),
  card(
    full_screen = TRUE,
    card_header("My plot"),
    plotOutput("p")
  )
)
  
server <- function(input, output) {
  output$p <- renderPlot({
    ggplot(mtcars) + geom_histogram(aes(!!input$var))
  })
}

shinyApp(ui, server)

Instead of these var select input can there be a way to replace these with navigable page like in bootstrap example.


Solution

  • You need to use Bootstrap's navigation components (aka navs).

    With the help of the documentation you see the markup you need, and the functionality works out of the box without additional JavaScript:

    library(shiny)
    library(ggplot2)
    library(bslib)
    
    ui <- page_sidebar(
      title = "Example dashboard",
      sidebar = sidebar(
        div(
          class = "nav flex-column nav-pills",
          id = "mynav-tab",
          role = "tablist",
          `aria-orientation` = "vertical",
          lapply(LETTERS[1:3], 
                 \(x) tags$a(class = paste0("nav-link", ifelse(x == "A", " active", "")),
                             id = paste0(x, "-tab"),
                             `data-toggle` = "pill",
                             href = paste0("#", x, "-tab-content"),
                             role = "tab",
                             `aria-controls` = paste0(x, "-tab-content"),
                             `aria-selected` = x == "A",
                             x)
          )
        )
      ),
      div(
        class = "tab-content",
        id = "mynav-tab-content",
        lapply(LETTERS[1:3],
               \(x) div(class = paste0("tab-pane fade", ifelse(x == "A", " show active", "")),
                        id = paste0(x, "-tab-content"),
                        role = "tabpanel",
                        `aria-labelledby` = paste0(x, "-tab"),
                        card(full_Screen = T,
                             card_header(x))
               )
        )
      )
    )
    
    server <- function(input, output) {
    }
    
    shinyApp(ui, server)
    

    Gif showing a navbar design and a click to the elements in it change the content in the main panel