Skip to content

Instantly share code, notes, and snippets.

@hafen
Last active December 10, 2015 04:48
Show Gist options
  • Save hafen/4383290 to your computer and use it in GitHub Desktop.
Save hafen/4383290 to your computer and use it in GitHub Desktop.
Shiny dynamic number of UI elements example
library(shiny)
MAX <- 200
shinyServer(function(input, output) {
# input$nInputs will be changed infrequently
# but input$dummy will be changed frequently
nInputs <- reactive(function() {
# it would be nice to be able add some code here
# to make sure that
# dynamicOutput_1 ... dynamicOutput_{nInputs}
# are enabled and
# dynamicOutput_{nInputs+1} ... dynamicOutput_{MAX}
# are disabled
input$nInputs
})
output$dynamicOutputContainer <- reactiveUI(function() {
res <- div()
# building the html in this way is not optimal
# perhaps tagAppendChildren would be a nice function
# to pass a list of children instead of one child
for(i in seq_len(nInputs())) {
res <- tagAppendChild(res, div(id=paste("dynamicOutput_", i, sep=""), class="shiny-html-output"))
}
res
})
# note that this doesn't work with a for loop
lapply(seq_len(MAX), function(i) {
output[['impl']]$defineOutput(
paste("dynamicOutput_", i, sep=""),
reactive(function() {
paste("Dynamic input ", i, " will go here but it depends on input dummy=", input$dummy, sep="")
})
)
})
})
library(shiny)
MAX <- 200
shinyUI(pageWithSidebar(
headerPanel("Dynamic number of UI elements example"),
sidebarPanel(
numericInput("nInputs", "Number of inputs:", 10, 1, MAX),
numericInput("dummy", "Dummy Input:", 10)
),
mainPanel(
htmlOutput("dynamicOutputContainer")
)
))
@ziyadsaeed
Copy link

This gist no longer works with current version of shiny

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