I have a large app that implements a dynamic UI. Given the need to update only a single element at a time, I moved away from using renderUI()
and was able to use the insertUI()
function to successfully add/remove the UI elements needed for the project.
They work as expected with a small caveat: the DOM is not updated to reflect the selected elements as they are with renderUI(), i.e. the selected
attribute is never added to the option
elements. Is this by design or a bug?
Please inspect the DOM in the following app after a selectInput()
and verbatimTextOutput()
pair has been added and some selections have been made.
library(shiny)
# Code license: MIT
# Using selectInput(selectize = FALSE) with insertUI()
# by Tim Thomas
# adapated from work by Bárbara Borges
ui <- fluidPage(
actionButton('insertBtn', 'Insert'),
actionButton('removeBtn', 'Remove'),
tags$div(id = 'placeholder')
)
server <- function(input, output) {
ids <- c()
observeEvent(input$insertBtn, {
id <- paste0(input$insertBtn)
ids <<- c(id, ids)
div_id <- paste0("div_", id)
select_id <- paste0("select_", id)
output_id <- paste0("output_", id)
choices <- lapply(1:4, function(x) {paste("Choice", x)})
insertUI(
selector = '#placeholder',
ui = tags$div(
id = div_id,
selectInput(select_id,
select_id,
choices,
multiple = TRUE,
selectize = FALSE),
verbatimTextOutput(output_id)
)
)
output[[output_id]] <- renderText(input[[select_id]])
})
observeEvent(input$removeBtn, {
removeUI(
selector = paste0('#div_', ids[length(ids)])
)
ids <<- ids[-length(ids)]
})
}
shinyApp(ui, server)