How to collapse sidebarPanel in shiny app?

守給你的承諾、 提交于 2019-11-28 01:03:47

问题


I have a shiny app with a mainPanel and a sidebarPanel inside a tabPanel in a navbarPage. I need an option to hide the sidebarPanel similar to this: Hide sidebar in default in shinydashboard and https://github.com/daattali/shinyjs/issues/43.

An actionButton should control if the sidebarPanel is shown or collapsed.

This is the code:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  navbarPage("",
             tabPanel("tab",
                      sidebarPanel(
                        useShinyjs()
                      ),

                      mainPanel(actionButton("showSidebar", "Show sidebar"),
                                actionButton("hideSidebar", "Hide sidebar")
                      )
             )
  )
)

server <-function(input, output, session) {
  observeEvent(input$showSidebar, {
    shinyjs::removeClass(selector = "body", class = "sidebarPanel-collapse")
  })
  observeEvent(input$hideSidebar, {
    shinyjs::addClass(selector = "body", class = "sidebarPanel-collapse")
  })
}

shinyApp(ui, server)

Hope somebody can help :)


回答1:


I have modified your code to hide and show the sidebar. To create the id for the sidebarPanelI have enclosed it within div and given it theid = Sidebar. To show and hide the side bar I have used shinyjs function show and hide with the id as Sidebar.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  navbarPage("",
             tabPanel("tab",
                      div( id ="Sidebar",sidebarPanel(
                      )),


                      mainPanel(actionButton("showSidebar", "Show sidebar"),
                                actionButton("hideSidebar", "Hide sidebar")
                      )
             )
  )
)

server <-function(input, output, session) {
  observeEvent(input$showSidebar, {
    shinyjs::show(id = "Sidebar")
  })
  observeEvent(input$hideSidebar, {
    shinyjs::hide(id = "Sidebar")
  })
}

shinyApp(ui, server)  

Hope it helps!




回答2:


An example of the toggle option suggested in previous comments.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  navbarPage("",
             tabPanel("tab",
                      div( id ="Sidebar",sidebarPanel(
                      )),


                      mainPanel(actionButton("toggleSidebar", "Toggle sidebar")
                      )
             )
  )
)

server <-function(input, output, session) {
  observeEvent(input$toggleSidebar, {
    shinyjs::toggle(id = "Sidebar")
  })
}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/42159804/how-to-collapse-sidebarpanel-in-shiny-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!