Last active
March 21, 2023 15:16
-
-
Save mine-cetinkaya-rundel/0fe2a9830f7151e72053239e73350592 to your computer and use it in GitHub Desktop.
Shiny dynamic UI - observers & lapply
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there a reason why using = over <- ?