Skip to content

Instantly share code, notes, and snippets.

@mine-cetinkaya-rundel
Last active November 8, 2017 21:38
Show Gist options
  • Save mine-cetinkaya-rundel/2f2081842ecd30ba251cf464fadb03f2 to your computer and use it in GitHub Desktop.
Save mine-cetinkaya-rundel/2f2081842ecd30ba251cf464fadb03f2 to your computer and use it in GitHub Desktop.
Shiny dynamic UI - observers & for loop
# An example based on http://shiny.rstudio.com/articles/dynamic-ui.html
library(shiny)
ui = basicPage(
fluidRow(
actionButton(inputId = "add_buttons", label = "Add 5 Buttons")
),
uiOutput("more_buttons") # this is where the dynamically added buttons will go
)
server = function(input, output)
{
# We need to track the actionButtons and their respective observeEvents
rvs = reactiveValues(buttons = list(), observers = list())
observeEvent(input$add_buttons, {
l = length(rvs$buttons) + 1
for(i in l:(l+4)) {
rvs$buttons[[i]] = actionButton(inputId = paste0("button",i), label = i)
rvs$observers[[i]] = observeEvent(input[[paste0("button",i)]], {
print(sprintf("You clicked button number %d",i))
}
)
}
}
)
output$more_buttons = renderUI({
do.call(fluidRow, rvs$buttons) # Add the dynamic buttons into a single fluidRow
})
}
shinyApp(ui, server)
@nfultz
Copy link

nfultz commented Nov 8, 2017

I tried running this, but when I click on buttons 1-4 nothing happens, and when I click on button 5, [1] "You clicked button number 5" gets printed 5 times. :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment