Skip to content

Instantly share code, notes, and snippets.

@mine-cetinkaya-rundel
Last active March 21, 2023 15:16
Show Gist options
  • Save mine-cetinkaya-rundel/0fe2a9830f7151e72053239e73350592 to your computer and use it in GitHub Desktop.
Save mine-cetinkaya-rundel/0fe2a9830f7151e72053239e73350592 to your computer and use it in GitHub Desktop.
Shiny dynamic UI - observers & lapply
# 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 = lapply(
l:(l+4),
function(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)
@zalazhar
Copy link

zalazhar commented Oct 6, 2018

is there a reason why using = over <- ?

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