Search code examples
rshinytabs

Removing tabPanel(s) with same title in shiny


In base of this, what I want is

  1. Allow multiple tabs with the same title
  2. The button remove to remove the current selected tab

I tried the following:

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton("add", "Add Other tab"),
      actionButton("remove", "Remove Current tab")
    ),
    mainPanel(
      tabsetPanel(id = "tabs"
                  ,tabPanel("Java", "tab for Java")
                  ,tabPanel("C++", "tab for C++")
                  ,tabPanel("Python", "tab for Python")
                  ,tabPanel("Python", "tab for Python")
                  
      )
    )
  )
)
server <- function(input, output, session) {
  observeEvent(input$add, {
    insertTab(inputId = "tabs",
              tabPanel("Other language", "tab for other language"),
              select=TRUE
    )
  })
  observeEvent(input$remove, {
    removeTab(inputId = "tabs", target = input$tabs)
  })
}

shinyApp(ui, server)

However, when I selected the last "Python" tab and then click on the button remove, all the tabs with "Python" title are removed. I want only to remove the selected tab.

Is there any way to achieve this?


Solution

  • The problem

    The removeTab() docs set out that the target parameter should be:

    the value of the tabPanel that you want to remove.

    The default parameters for tabPanel() are tabPanel(title, ..., value = title, icon = NULL).

    As you are creating two tabs with identical titles, "Python", they have the same value, so removeTab(inputId = "tabs", target = "Python") will delete them both.

    The solution

    Simply create your Python tabs with different values:

    tabsetPanel(id = "tabs"
        ,tabPanel("Java", "tab for Java")
        ,tabPanel("C++", "tab for C++")
        ,tabPanel("Python", "tab for Python", value = "python1")
        ,tabPanel("Python", "tab for Python", value = "python2")
                      
    )
    

    As you can see below, when you click the Remove current tab button it now only deletes the selected tab:

    enter image description here