1

I'm trying to design a Shiny app such that a user can click on buttons to add or remove a tabPanel. I've been able to do this successfully with the code below, but there is a problem. In the code below every time the user clicks on Add L2 or Remove L2, the entire panel is recreated, thus resetting all inputs in each tabPanel. This is problematic because the goal is for the user to dynamically add tabPanels and save their inputs. Is there any way to do this?

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(width = 3, fixed=T,
      h3("L2 Machine"),
      actionButton('moreL2', tags$b('Add L2')),
      actionButton('lessL2', tags$b('Remove L2')),
      uiOutput('panelset')
    ),
    mainPanel(
    )
  )
)

server <- function(input, output) {
  more <- reactiveValues(i=1)
  less <- reactiveValues(i=1)
  observe({
    input$moreL2
    isolate({
      more$i <- more$i + 1
    })
  })
  observe({
    input$lessL2
    isolate({
      less$i <- less$i + 1
    })
  })

  output$panelset <- renderUI({
    if(less$i > more$i) less$i <- more$i

    n <- seq(max(more$i - less$i + 1, 1))
    lapply(n, function(i) {
      tabPanel(
        title = paste0('Pan', i),
        numericInput(paste0('L2amount', i), 'Select L2 Amount', value = 0),
        selectInput(paste0('L2type', i), 'Select L2 Type', c('Percent', 'Absolute')),
        dateRangeInput(paste0('L2daterange',i), 'Select Adjustment Period', 
          start='01-01-2010', end='01-12-2015'))
    })
  })
}

shinyApp(ui, server)
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • I think the key is to render each tabPanel separately. If you know the max number of panels in advance, you can create that many `uiOutput` and only render the new ones as needed. – Xiongbing Jin May 10 '16 at 17:41
  • 1
    I posted an answer to a similar question [here](http://stackoverflow.com/questions/35020810/dynamically-creating-tabs-with-plots-in-shiny-without-re-creating-existing-tabs/), without the deleting part. But it would be very easy to write a function that deletes tabPanels. If you'd like some further details, I could adapt this to your case. – K. Rohde May 11 '16 at 08:15
  • Thanks for the help. @K.Rohde, I'll take a look at the code and see if I can adapt it. I'm not too familiar with JavaScript so that might be a bit of a challenge for me. – Gaurav Bansal May 11 '16 at 14:18

0 Answers0