Dynamic UI with renderUI and insertUI
Generate UI elements on-the-fly based on user input and server state.
Dynamic UI — Why and When
Sometimes the UI you need cannot be fully determined at app startup — it depends on user choices, loaded data, or runtime conditions. Shiny provides two mechanisms: renderUI() for replacing a placeholder's entire contents, and insertUI()/removeUI() for adding or removing elements without replacing everything.
library(shiny)
# Static UI: columns always shown
# ui <- fluidPage(selectInput('x', ...), selectInput('y', ...))
# Dynamic UI: columns depend on which dataset was loaded
# ui <- fluidPage(fileInput('upload', ...), uiOutput('var_selectors'))renderUI() and uiOutput()
renderUI({...}) in the server builds and returns a UI element reactively. uiOutput('id') in the UI creates a placeholder that displays whatever renderUI produces. The entire content of the placeholder is replaced each time the reactive reruns.
ui <- fluidPage(
selectInput('dataset', 'Dataset:', choices = c('iris', 'mtcars')),
uiOutput('column_selector') # placeholder
)
server <- function(input, output, session) {
output$column_selector <- renderUI({
df <- get(input$dataset) # reactive dependency on dataset
selectInput('col', 'Choose Column:',
choices = names(df))
})
}
shinyApp(ui, server)All lessons in this course
- Reactive Programming Deep Dive
- Shiny Modules for Code Reuse
- Dynamic UI with renderUI and insertUI
- Deploying Shiny Apps