R shinydashboard dynamic menu selection

六月ゝ 毕业季﹏ 提交于 2019-11-30 15:47:34

问题


I have created dynamic sibebar menus in R shinydashboard. Even though I use selected = TRUE, no menuItem associated with a menu gets selected at startup in this dynamic mode.

How can I make sure I have control on which menuItem's contents is shown at startup in this dynamic mode?

I have been searching all over through similar posts. Could not find anything that work so far. updateTabItems() did not seem to work.

Any ideas? thanks from advance.

library(shiny)
library(shinydashboard)
ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenuOutput("menu")
  ),
  dashboardBody(
        tabItems(
          tabItem(tabName = "m1", p("Menu content 1") ),
          tabItem(tabName = "m2", p("Menu content 2") )
    )
   )
)
server <- function(input, output) {
  output$menu <- renderMenu({
    sidebarMenu(
      menuItem("Menu item1", tabName="m1", icon = icon("calendar")),
      menuItem("Menu item2", tabName="m2", icon = icon("database"),selected = TRUE)
    )
  })
}
shinyApp(ui, server)

Edit : Indentation problem that occurs with Romain's anwser


回答1:


You have effectively to use updateTabItems(). To do so you have to set up an id for the sidebarMenu and update the corresponding menuItem or menuSubItem.

For your specific case you should do something like this:

library(shiny)
library(shinydashboard)
ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenu(id="tabs",
    sidebarMenuOutput("menu")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "m1", p("Menu content 1") ),
      tabItem(tabName = "m2", p("Menu content 2") )
    )
  )
)
server <- function(input, output,session) {

  output$menu <- renderMenu({
    sidebarMenu(
           menuItem("Menu item1", tabName="m1", icon = icon("calendar")),
           menuItem("Menu item2", tabName="m2", icon = icon("database"))
           )
  })
  isolate({updateTabItems(session, "tabs", "m2")})
}
shinyApp(ui, server)

Edited version to remove the indentation problem




回答2:


Why not using an observer which is called only once at app init

observe({ # called only once at app init
  updateTabItems(session, "tabs", "m2")
})


来源:https://stackoverflow.com/questions/36742932/r-shinydashboard-dynamic-menu-selection

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