Search code examples
rshinyshinydashboard

Why is the sidebar not disappearing when I click the sidebar toggle button?


I changed the width of the sidebar on my Shiny dashboard but when I press the sidebar toggle button, the sidebar doesn't disappear completely.

This is how it looks like after pressing the button:

enter image description here

I am using a .css file and I would like to include a line in this file to solve the problem.


Solution

  • This has to do with shinydashboard passing any custom width parameters provided by the user in the dashboardSidebar() function into some custom CSS. If we provide a minimal reproducible example like so, we can see this in the app if we right click > Inspect.

    library(shiny)
    library(shinydashboard)
    
    ui <- dashboardPage(
      header = dashboardHeader(),
      body = dashboardBody(),
      sidebar = dashboardSidebar(
        sidebarMenu(),
        width = "10%"
      )
    )
    
    server <- function(input, output, session) {}
    
    shinyApp(ui, server)
    

    MRE Shinydashboard App with partially collapsed sidebar The red box in the screenshot shows the HTML elements corresponding to the sidebar (note the data-collapsed="true" to indicate the sidebar is currently in its collapsed form). The yellow box shows the CSS styles that control its appearance when collapsed. In this example, we've specified width = "10%" so that is passed to transform: translate(-10%, 0); in the CSS. If we instead add some custom CSS to override this behavior, then the sidebar collapses as normal:

    ui <- dashboardPage(
      header = dashboardHeader(),
      body = dashboardBody(),
      sidebar = dashboardSidebar(
        sidebarMenu(),
        width = "10%",
        tags$style(
          "@media (min-width: 768px) {
            .sidebar-collapse .main-sidebar,
            .sidebar-collapse .left-side {
              transform: translate(-100%, 0) !important;
            }
          }"
        )
      )
    )
    

    Then the sidebar always fully collapses, e.g., because we've now hard-coded transform: translate(-100%, 0). Again, note the data-collapsed="true" indicating the sidebar has been collapsed. Hope this helps! MRE Shinydashboard Fully Collapsed Sidebar