DelTrader
DelTrader

Reputation: 19

Returns DF information after clicking menu based on ID (Shiny)

In the Shiny code below, I need to return to the dashboardBody() "You chose 'name'" using the selected menu id. Improvement of the current code will be appreciated, I'm learning and migrating my R Script project to Shiny.

library(shiny)
library(shinydashboard)

labels = data.frame(id = c(seq.int(nrow(mtcars))),
                    name = c(rownames(mtcars)))

##### UI ##### 
ui <- dashboardPage(
    dashboardHeader(title = "Example"),
    
    dashboardSidebar(
        sidebarMenu(id="mytabs",
                    sidebarMenuOutput("menu"))
    ),
    
    dashboardBody()
)

##### SERVER #####
server <- function(input, output, session) {
    output$menu <- renderMenu({
        myTabs = lapply(1:nrow(labels) , function(i) {
            menuItem(labels$name[i], tabName = labels$id[i])
        })
        do.call(sidebarMenu, myTabs)
    })
}

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

Upvotes: 0

Views: 16

Answers (1)

stefan
stefan

Reputation: 125338

This could be achieved like so:

  1. You can get the id of the chosen menu item via input$mytabs and
  2. the label via labels$name[as.integer(input$mytabs)]
    library(shiny)
    library(shinydashboard)
    
    labels = data.frame(id = c(seq.int(nrow(mtcars))),
                        name = c(rownames(mtcars)))
    
    ##### UI ##### 
    ui <- dashboardPage(
      dashboardHeader(title = "Example"),
      
      dashboardSidebar(
        sidebarMenu(id="mytabs",
                    sidebarMenuOutput("menu"))
      ),
      
      dashboardBody(
        textOutput("text")
      )
    )
    
    ##### SERVER #####
    server <- function(input, output, session) {
      output$menu <- renderMenu({
        myTabs = lapply(1:nrow(labels) , function(i) {
          menuItem(labels$name[i], tabName = labels$id[i])
        })
        do.call(sidebarMenu, myTabs)
      })
      
      output$text <- reactive({
        req(input$mytabs)
        paste("You chose", labels$name[as.integer(input$mytabs)])
      })
    }
    
    ##### Run the application #####
    shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions