R Shiny: name tabPanel with the number of clicks

Viewed 388

I'm creating an app in which the user can create new tabPanels by clicking on a tabPanel dedicated to it. I know how to do so, but I don't know how to name tabPanels with a reactive number in it.

To be clearer, here's a reproducible example:

library(shiny)
library(shinyWidgets)

ui <- navbarPage(position = "static-top",
                 title = "foo",
                 id = "tabs",
                 tabPanel(title = "Name 1",
                          fluidRow()),
                 tabPanel(title = "More",
                          icon = icon("plus"),
                          fluidRow()
                          )
                 )


server <- function(input, output) {

  count <- reactive({
    i <- 1
      if (input$tabs == "More"){
        i <- i + 1
      }
      else {i <- i}
    i
  })

  observeEvent(input$tabs, {
    id = paste0("Name ", count())
    if (input$tabs == "More")
    appendTab(inputId = "tabs",
              tabPanel(title = id,
                       fluidRow(column(
                         width = 12))
              ),
              select = TRUE)
  })

}


shinyApp(ui = ui, server = server)

As you can see, clicking on the tabPanel More creates a new tabPanel. I would like the names of tabPanels to be of the form "Name i" where "i" is the number of tabPanels existing (- 1 because I don't want to take into account the tabPanel More and + 1 to prevent having twice the same number at the beginning). Therefore, I need this "i" to be reactive because it will have to take into account the user-created tabPanels.

In my code, you can see I've tried to count the number of tabPanels by counting the number of clicks on the tabPanel More but that doesn't work. I saw this post but I don't know how to modify it since I've never used JavaScript.

Does anybody have a solution?

1 Answers

You can make count() a reactiveVal to solve this:

Furthermore you might want to use insertTab instead of appendTab to keep the "More"-Tab on the right:

library(shiny)
library(shinyWidgets)

ui <- navbarPage(position = "static-top",
                 title = "foo",
                 id = "tabs",
                 tabPanel(title = "Name 1",
                          fluidRow()),
                 tabPanel(title = "More",
                          icon = icon("plus"),
                          fluidRow()
                 )
)


server <- function(input, output) {

  count <- reactiveVal(1)

  observeEvent(input$tabs, {
    if (input$tabs == "More"){
      count(count()+1)
      id = paste0("Name ", count())
      insertTab(inputId = "tabs",
                tabPanel(title = id,
                         fluidRow(column(
                           width = 12))
                ), target = "More", position = "before",
                select = TRUE)}
  })

}


shinyApp(ui = ui, server = server)
Related