Geovany Geovany - 4 months ago 109
R Question

how to manually expand a submenu in a shiny dashboard side bar

I'm trying to manually expand a submenu in a sidebar in shiny dashboard. The

updateTabItems
function only works with normal menus, but not with nested menus.

Here is basic example (modified from the
updateTabItems
documentation) to show the problem. If I clicked on 'Switch tab', it switches the menus, but it doesn't expand the first menu that has a submenu. It seems that it only selected the submenu but doesn't expand the tree.

library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Simple tabs"),
dashboardSidebar(
sidebarMenu(
id = "tabs",
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"),
menuSubItem("Sub Menu 1",icon = icon("folder-open"), tabName = "subMenu1")
),
menuItem("Widgets", tabName = "widgets", icon = icon("th"))
),
actionButton('switchtab', 'Switch tab')
),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
h2("Dashboard tab content")
),
tabItem(tabName = "widgets",
h2("Widgets tab content")
)
)
)
)

server <- function(input, output, session) {
observeEvent(input$switchtab, {
newtab <- switch(input$tabs,
"subMenu1" = "widgets",
"widgets" = "subMenu1"
)
updateTabItems(session, "tabs", newtab)
})
}

shinyApp(ui, server)
}


I would like manually expand the tree, select the menu and the submenu. Any suggestions are welcome. Thanks.

Answer

I helped myself out defining some JavaScript, using the JavaScript interface extendShinyjs in shiny:

js$selectMenuItem(0)
js$selectMenuSubItem(2)

useShinyjs(), 
extendShinyjs(text = jsSelectMenuItem), 
extendShinyjs(text = jsSelectMenuSubItem)

select menuItem i

jsSelectMenuItem <- "shinyjs.selectMenuItem = function(i){
    setTimeout(function(){
        $('.treeview > a').eq(i).click();
    }, 200);
}"

select menuSubItem i

jsSelectMenuSubItem <- "shinyjs.selectMenuSubItem = function(i){
    setTimeout(function(){
        $('.treeview-menu > li > a').eq(i).click();
    }, 800);
}"