iomedee
iomedee

Reputation: 393

Shiny: how to select opened the first subitem in menu

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)

Upvotes: 3

Views: 1518

Answers (1)

qfazille
qfazille

Reputation: 1671

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)

Upvotes: 6

Related Questions