Search code examples
rshinyshinydashboard

Toggle display of sidebar menu in shinydashboard programmatically


I am working with R shiny dashboard and was wondering if I can collapse/show the sidebar with an additional button, just like the already existing one on top of the sidebar. Is that possible?

Cheers


Solution

  • You can add / remove the needed css class to / from the body via shinyjs:

    library(shiny)
    library(shinyjs)
    library(shinydashboard)
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
        shinyjs::useShinyjs(),
        actionButton("toggle_btn", "Toggle sidebar")
      )
    )
    
    server <- function(input, output, session) {
      observeEvent(input$toggle_btn, {
        shinyjs::toggleClass(selector = "body", class = "sidebar-collapse")
      })
    }
    
    shinyApp(ui, server)
    

    result