R shinydashboard - show/hide multiple menuItems based on user input

筅森魡賤 提交于 2019-12-04 21:57:10

Here is an idea for growing your sidebarMenu dynamically using renderUI and uiOutput. It is also fairly straightforward to convert to a for loop if your number of tabs grows.


library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(title = "SHOW/HIDE MULTIPLE MENU ITEMS"),
  dashboardSidebar(
    useShinyjs(),
    uiOutput('sidebar'),
    textInput(inputId = "accessToken", label = "Access Code", value = "Show/Hide Menu Items.")
  ),
  dashboardBody()

)

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

  output$sidebar <- renderUI({

    menu_items = list()

    if(substr(input$accessToken,1,1)=='1')
      menu_items[[length(menu_items)+1]] = menuItem("MENU ITEM 1", tabName = "mi1")

    if(substr(input$accessToken,2,2)=='1')
      menu_items[[length(menu_items)+1]] = menuItem("MENU ITEM 2", tabName = "mi2")

    if(substr(input$accessToken,3,3)=='1')
      menu_items[[length(menu_items)+1]] = menuItem("MENU ITEM 3", tabName = "mi3")

    print(menu_items)

    sidebarMenu(id = "tabs",menu_items)

  })
}

shinyApp(ui, server)

Hope this helps!

This is for future readers.

Florian answer was helpful but since I wanted to keep my menuItems in dashboardSidebar. I spent some more time and realized I was using the paste0 incorrectly.

I ended up using the following:

observeEvent(input$accessToken, {
 tokenStr <- strsplit(input$accessToken, "")[[1]]
 tokenLen <- length(tokenStr)

 if(tokenLen == 3){
  tokenStrShow <- which(tokenStr=="1")
  tokenStrHide <- which(tokenStr=="0")
  for (i in tokenStrShow){
    show(selector= paste0("ul li:eq(",i - 1,")"))
  } 
  for (i in tokenStrHide){
    hide(selector= paste0("ul li:eq(",i - 1,")"))
  }
}

})

The advantages of this method were:

  • I was able to keep my dashboardSidebar as it is. (This was needed for my project)
  • Easily extendable for an increasing number of menuItems. ( only requires editing tokenLen
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!