Last active
November 8, 2017 21:38
-
-
Save mine-cetinkaya-rundel/2f2081842ecd30ba251cf464fadb03f2 to your computer and use it in GitHub Desktop.
Shiny dynamic UI - observers & for loop
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[[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
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. :(