Add a new tab in tabItems

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)
1 Like

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

hello,
thank for your help.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.