Skip to content

Instantly share code, notes, and snippets.

@nfultz
Forked from mine-cetinkaya-rundel/app.R
Last active November 8, 2017 21:39
Show Gist options
  • Save nfultz/bcd1d1213ab92f1986e817165c904f95 to your computer and use it in GitHub Desktop.
Save nfultz/bcd1d1213ab92f1986e817165c904f95 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]] = local({
i <- 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment