Add a new tab in tabItems

shinydashboard
#1

Hello,

I am learning shiny and shinydashboard. I would like to add a tab in when pressing a button, so I use the function insertTab () but nothing happens.

library(shiny)
library(shinydashboard)

# Define UI for application that draws a histogram
ui <- dashboardPage(
  dashboardHeader(),
  
  dashboardSidebar(
    sidebarMenu(
      menuItem("menu1", tabName = "menu1", icon = icon("table"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "menu1",
        navbarPage("",
                   tabPanel("tab1.1", fluidPage(
                     actionButton(inputId = "button", label = "Click Me")
                   )),
                   tabPanel("tab1.2")
        )
      )
    )
  )
  
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
   
  observeEvent(input$button, {
    insertTab(inputId = "tab1.3",
              tabPanel("Dynamic", "This a dynamically-added tab"),
              position = 'after',
              target = "tab1.2"
    )
    
  })
  
}

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

#2

Two changes made.

  • navbarPage needs an id value. I used id = "myNavbar".
  • insertTab's inputId should point to the navbarPage's id.

Updated Code:

library(shiny)
library(shinydashboard)

# Define UI for application that draws a histogram
ui <- dashboardPage(
  dashboardHeader(),
  
  dashboardSidebar(
    sidebarMenu(
      menuItem("menu1", tabName = "menu1", icon = icon("table"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "menu1",
        navbarPage("", id = "myNavbar",
                   tabPanel("tab1.1", fluidPage(
                     actionButton(inputId = "button", label = "Click Me")
                   )),
                   tabPanel("tab1.2")
        )
      )
    )
  )
  
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
   
  observeEvent(input$button, {
    insertTab(inputId = "myNavbar",
              tabPanel("Dynamic", "This a dynamically-added tab"),
              position = 'after',
              target = "tab1.2"
    )
    
  })
  
}

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

#3

hello,
thank for your help.

1 Like