Shiny: how to select opened the first subitem in menu

爱⌒轻易说出口 提交于 2021-01-27 20:31:46

问题


I have quite complicated shiny app whose all menuItems are rendered inside the server part. It's been necessary to do. And now I can't find the solution how to select opened the first subitem in menu. The first page is just blank.

library(shiny)
library(shinydashboard)


ui <- dashboardPage(
  dashboardHeader(
    title = "Shiny"
  ),

  dashboardSidebar(
    sidebarMenu(

      menuItemOutput("Section_1")

    )
  ),

  dashboardBody(

    tabItems(
      tabItem("report_1",h1("a")),
      tabItem("report_2",h1("b")),
      tabItem("report_3",h1("c"))
    )
  )
)


server <- function(input, output) {

    output$Section_1 <- renderMenu({

      menuItem("Section_1", tabName = "section_1", icon = icon("align-justify"), 
               startExpanded = TRUE, selected = TRUE,
               menuSubItem("Subsection 1", tabName = "report_1", selected = TRUE),
               menuSubItem("Subsection 2", tabName = "report_2"),
               menuSubItem("Subsection 3", tabName = "report_3"))

    })

}

shinyApp(ui,server)

回答1:


You can add an id to your sidebarMenu and then select a tabName from and observer

library(shiny)
library(shinydashboard)


ui <- dashboardPage(
    dashboardHeader(
        title = "Shiny"
    ),

    dashboardSidebar(
        sidebarMenu(id = "tabs",
            menuItemOutput("Section_1")
        )
    ),

    dashboardBody(

        tabItems(
            tabItem("report_1",h1("a")),
            tabItem("report_2",h1("b")),
            tabItem("report_3",h1("c"))
        )
    )
)


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

    output$Section_1 <- renderMenu({

        menuItem("Section_1", tabName = "section_1", icon = icon("align-justify"), startExpanded = TRUE,
                 menuSubItem("Subsection 1", tabName = "report_1"),
                 menuSubItem("Subsection 2", tabName = "report_2"),
                 menuSubItem("Subsection 3", tabName = "report_3")
        )

    })

    observe({
        updateTabItems(session, "tabs", selected = "report_1")
    })
}

shinyApp(ui,server)


来源:https://stackoverflow.com/questions/53279227/shiny-how-to-select-opened-the-first-subitem-in-menu

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