Sam Helmich Sam Helmich - 2 months ago 17
R Question

Dynamic number of actionButtons tied to unique observeEvent

I'd like to generate a dynamic number of actionButtons, and then have each generated button print its number to the console. This is my best attempt so far, but I still can't get the observeEvent for each of the first 10 buttons to recognize the button clicks. How do I tie the buttons to an observeEvent?

library(shiny)

ui <- basicPage(
fluidRow(
actionButton(inputId = "add_button",
label = "Add Button")
),
uiOutput("more_buttons")
)

server <- function(input, output){

rvs <- reactiveValues(buttons = list(actionButton(inputId = "button1",
label = 1)))

observeEvent(eventExpr = input$add_button,
handlerExpr = {
len <- length(rvs$buttons) + 1
rvs$buttons[[len]] <- actionButton(inputId = paste0("button",len),
label = len)
})

output$more_buttons <- renderUI({
do.call(fluidRow, rvs$buttons)
})

# This is the part that doesn't work
for(ii in 1:10){
observeEvent(eventExpr = input[[paste0("button",ii)]],
handlerExpr = print(ii))
}

}

shinyApp(ui, server)

Answer

Your really close, just wrap the observeEvent part in local.

library(shiny)

ui <- basicPage(
  fluidRow(
    actionButton(inputId = "add_button",
                 label = "Add Button")
  ),
  uiOutput("more_buttons")
)

server <- function(input, output){

  rvs <- reactiveValues(buttons = list(actionButton(inputId = "button1",
                                                    label = 1)))

  observeEvent(eventExpr = input$add_button,
               handlerExpr = {
                 len <- length(rvs$buttons) + 1
                 rvs$buttons[[len]] <- actionButton(inputId = paste0("button",len),
                                                    label = len)
               })

  output$more_buttons <- renderUI({
    do.call(fluidRow, rvs$buttons)
  })

  for(ii in 1:10){
    local({
      i <- ii
      observeEvent(eventExpr = input[[paste0("button",i)]],
                   handlerExpr = {print(i)})
    })

  }

}

shinyApp(ui, server)
Comments