11

Is there any way to manually disabling/enabling the sidebar on shiny dashboard app from the server side?

I would like to hide the sidebar automatically when I need more space without using toggle button on the header.

Thank you

DeanAttali
  • 25,268
  • 10
  • 92
  • 118
Geovany
  • 5,389
  • 21
  • 37

1 Answers1

19

I'm not very familiar with dashboards as I never built one, but from a taking a quick look, it seems like when clicking on the open/hide sidebar button, all that happens is a sidebar-collapse class gets added/removed to the <body> tag. Maybe more things happen that I'm unaware of, but that seemed to be the most visible thing.

So you can easily use shinyjs package (disclaimer: I'm the author) to add/remove that class

library(shiny)
library(shinydashboard)
library(shinyjs)

shinyApp(
  ui = 
    dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
        shinyjs::useShinyjs(),
        actionButton("showSidebar", "Show sidebar"),
        actionButton("hideSidebar", "Hide sidebar")
      )
    ),
  server = function(input, output, session) {
    observeEvent(input$showSidebar, {
      shinyjs::removeClass(selector = "body", class = "sidebar-collapse")
    })
    observeEvent(input$hideSidebar, {
      shinyjs::addClass(selector = "body", class = "sidebar-collapse")
    })
  }
)
Ferdi
  • 540
  • 3
  • 12
  • 23
DeanAttali
  • 25,268
  • 10
  • 92
  • 118
  • 2
    By the way, I'm using your library (shinyjs) since the first release. It is very useful for someone like me with a very basic experience with JS. I really like your approach for the library and actually I have learned a lot from the source code. So, thank you very much for creating shinyjs :) – Geovany Jul 09 '15 at 03:49
  • how would you adjust the location of `useShinyjs()` the selector variables if your `dashboardBody` is rendered dynamically? – road_to_quantdom Mar 25 '19 at 10:31