Append and remove tabs using sidebarPanel

Viewed 123

Having trouble deleting tabs that have been newly created in Shiny.

Scenario:

  1. Add new tab "A"
  2. Add new tab "B"
  3. Click delete on tab B - doesn't delete
  4. Select tab A, click delete it works

I feel its something to do with ids, stumped with the logic.

Thanks in advance.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  navbarPage(title = "Test", id="tabs",             
             tabPanel("Home",
                      sidebarPanel(
                        selectInput("testlist", "Select test:", 
                                    list("A", "B", "C")),
                        actionButton("append", "New tab")),
                     
                      mainPanel()
             )
  )
)


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

tabnamesinput<-reactive({
                         input$testlist
                        })
  
  
observeEvent(input$append,{
  id<-paste0(tabnamesinput()) 
  appendTab(inputId = "tabs",
            tabPanel(id,
                     sidebarPanel(
                       actionButton("remove", "Delete")
                     )
  )
  )
})

observeEvent(input$remove,{
  removeTab(inputId = "tabs", target = input$tabs)
})
}

shinyApp(ui, server)

1 Answers

With your above approach you are trying to assign the same id = "remove" to each delete-button. This won't work. Every button needs it's own id.

Once each button has it's unique id you need an observer listening to all events triggered by those buttons. The following looks for all inputs matching the pattern "^remove_":

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  navbarPage(title = "Test", id = "tabs",             
             tabPanel("Home",
                      sidebarPanel(
                        selectInput("testlist", "Select test:", list("A", "B", "C"), selected = "A"),
                        actionButton("append", "New tab")),
                      mainPanel()
             )
  )
)


server <- function(input, output, session) {
  
  observeEvent(input$append,{
    appendTab(inputId = "tabs",
              tabPanel(input$testlist,
                       sidebarPanel(
                         actionButton(paste0("remove_", input$testlist), "Delete")
                       )
              )
    )
  })
  
  observeEvent(lapply(grep(pattern = "^remove_", x = names(input), value = TRUE), function(x){input[[x]]}),{
    if(input$tabs != "Home"){
      removeTab(inputId = "tabs", target = input$tabs)
      updateSelectInput(session, "testlist", selected = input$testlist) # keep the selection when re-rendering sidebarPanel
    }
  })
}

shinyApp(ui, server)

result

Related