Skip to content

Instantly share code, notes, and snippets.

@cecilialee
Last active February 10, 2018 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilialee/80fabe4561bcefda2edacb1ca6830905 to your computer and use it in GitHub Desktop.
Save cecilialee/80fabe4561bcefda2edacb1ca6830905 to your computer and use it in GitHub Desktop.
Insert dynamic number of UI in Shiny. #r #shiny
# Using for loop
library(shiny)
ui = basicPage(
numericInput("n", "Number", 1, min = 1),
actionButton("add", "Add UI")
)
server = function(input, output, session) {
observeEvent(input$add, {
for (var in seq(input$n)) {
insertUI(
selector = "#add",
where = "afterEnd",
ui = textInput(paste0("txt", input$add),
"Insert some text")
)
}
})
}
shinyApp(ui, server)
# Using lapply
# Separate insertUI function and lapply function
library(shiny)
ui = basicPage(
numericInput("n", "Number", 1, min = 1),
actionButton("add", "Add UI")
)
server = function(input, output, session) {
insert_ui <- function() {
insertUI(
selector = "#add",
where = "afterEnd",
ui = textInput(paste0("txt", input$add),
"Insert some text")
)
}
observeEvent(input$add, {
lapply(seq(input$n), function(x) insert_ui())
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment