Skip to content

Instantly share code, notes, and snippets.

@strboul
Created June 5, 2019 18:29
Show Gist options
  • Save strboul/310dc3d546437f40429e7a837f1de07c to your computer and use it in GitHub Desktop.
Save strboul/310dc3d546437f40429e7a837f1de07c to your computer and use it in GitHub Desktop.
Shiny dynamically create actionButtons #observeEvent #renderUI #uiOutput
# UTILS -------------------------------------------------------------------
#' Generate input IDs for Shiny for dynamically generated elements
#'
#' @param prefix a meaningful text for the element e.g. button, table, slider etc.
#' @param id increase iteration from e.g. a loop.
#' @noRd
shinyInputId <- function(prefix, id) {
paste(prefix, id, sep = "_")
}
# DATA --------------------------------------------------------------------
mtcars <- datasets::mtcars
# APP ---------------------------------------------------------------------
ui <- fluidPage(
h1("Cars"),
br(),
lapply(seq(nrow(mtcars)), function(i) {
uiOutput(shinyInputId("button", i))
})
)
server <- function(input, output, session) {
lapply(seq(nrow(mtcars)), function(i) {
Name <- rownames(mtcars)[i]
gen.input <- shinyInputId("button", i)
output[[gen.input]] <- renderUI({
actionButton(
inputId = gen.input,
label = Name
)
})
observeEvent(input[[gen.input]], {
print(paste("You clicked", Name))
})
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment