rstudio / shinydashboard

Shiny Dashboarding framework
https://rstudio.github.io/shinydashboard/
Other
886 stars 300 forks source link

Collabsing sidbar for a selected tab based on tab id #316

Open teshomem opened 5 years ago

teshomem commented 5 years ago

Hi,

I am not able to hide the sidebar for a selected tab.

observeEvent(input$tabs == "tab1", { shinyjs::addClass(selector = "body", class = "sidebar-collapse") })

alandipert commented 5 years ago

Hi, would you please provide a complete standalone example that demonstrates the problem? Without knowing the structure of your overall UI it's hard for me to understand the problem you describe. Thank you in advance for the additional information.

teshomem commented 5 years ago

OK, I want to collapse or hide the sidebr menue when tab "B" is selected. I tried with observeEvent with no effect.

library(shiny)    
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenuOutput("menu")
  ),
  dashboardBody(

    textOutput("text"),
    tabsetPanel(id = "tabs",
                tabPanel("Tab A", value = "A", "This is Tab A content"),
                tabPanel("Tab B", value = "B", "Here's some content for tab B.")
    )

  ))

server <- shinyServer(function(input, output) {

  output$text <- renderText({paste0("You are viewing tab \"", input$tabs, "\"")})

  observeEvent(input$tabs == "B", {

    shinyjs::addClass(selector = "body", class = "sidebar-collapse")

  })

})
shinyApp(ui, server)

Thanks

alandipert commented 5 years ago

OK, thanks for that, I think I understand what you wanted now. Does the below work?

library(shiny)    
library(shinydashboard)

jsCode <- 'shinyjs.hideSidebar = function(){
  if (!$("#sidebarCollapsed").data("collapsed")) {
    $("a.sidebar-toggle").trigger("click")
  }
}'

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenuOutput("menu")
  ),
  dashboardBody(
    shinyjs::useShinyjs(),
    shinyjs::extendShinyjs(text = jsCode),
    textOutput("text"),
    tabsetPanel(id = "tabs",
                tabPanel("Tab A", value = "A", "This is Tab A content"),
                tabPanel("Tab B", value = "B", "Here's some content for tab B.")
    )

  ))

server <- shinyServer(function(input, output) {

  showSidebar <- reactiveVal(TRUE)

  output$text <- renderText({paste0("You are viewing tab \"", input$tabs, "\"")})

  observeEvent(input$tabs, {
    if (input$tabs == "B") {
      shinyjs::js$hideSidebar()
    }
  })

})
shinyApp(ui, server)
teshomem commented 5 years ago

@alandipert thanks a lot. Almost there :-) Your current solution affects Tab A too. I want the effect only for Tab B. I have multiple tabs but some of them have nothing in the sidebar Menu. So i wanted to hide the sidebar menu for selected tabs. Either when we click on them or permanently through some option in the dashboardSidebar. Thanks.