0

In this App (code below), I would like that the output "Selected Menu Item:" be followed by the name of the tabName of the menuSubItem the user clicked - example: "Selected Menu Item: sub1". Here's the code I unsucessfully tried.

library(shiny)
library(shinydashboard)

# Define UI for app
ui <- dashboardPage(
  dashboardHeader(title = "Example App"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Tab 1", tabName = "tab1",
               menuSubItem("SubTab 1", tabName= "sub1"),
               menuSubItem("SubTab 2", tabName= "sub2"))
    )
  ),
  dashboardBody(
    h3("Selected Menu:"),
    verbatimTextOutput("selected_menu")
  )
)

# Define server logic
server <- function(input, output, session) {
  
  # render the selected menu item as text
  output$selected_menu <- renderText({
    paste("Selected Menu Item:", input$tabs)
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)
stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

1

To make your code work and to access the selected tab you have to add an id named "tabs" to your sidebarMenu:

library(shiny)
library(shinydashboard)

# Define UI for app
ui <- dashboardPage(
  dashboardHeader(title = "Example App"),
  dashboardSidebar(
    sidebarMenu(
      id = "tabs",
      menuItem("Tab 1",
        tabName = "tab1",
        menuSubItem("SubTab 1", tabName = "sub1"),
        menuSubItem("SubTab 2", tabName = "sub2")
      )
    )
  ),
  dashboardBody(
    h3("Selected Menu:"),
    verbatimTextOutput("selected_menu")
  )
)

# Define server logic
server <- function(input, output, session) {
  # render the selected menu item as text
  output$selected_menu <- renderText({
    paste("Selected Menu Item:", input$tabs)
  })
}

# Run the application
shinyApp(ui = ui, server = server)

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51