Skip to content

Instantly share code, notes, and snippets.

@ChrKoenig
Created June 19, 2022 19:34
Show Gist options
  • Save ChrKoenig/b9547c3cc7e49ec21805c286f0858c24 to your computer and use it in GitHub Desktop.
Save ChrKoenig/b9547c3cc7e49ec21805c286f0858c24 to your computer and use it in GitHub Desktop.
Insert/Remove UI elements in R Shiny
library(shiny)
ui = fluidPage(
titlePanel("My favorite movies"),
hr(),
# ------------------------------------- #
# Input form
tags$h3("Input form"),
fluidRow(
column(4, tags$label("Title")),
column(4, tags$label("Director")),
column(3, tags$label("Year released"))
),
div(id = "placeholder"),
actionButton(inputId = "new_row", label = "Add new movie", icon = icon("plus")),
# ------------------------------------- #
# Print user inputs
hr(),
tags$h3("User Inputs"),
tableOutput("user_inputs")
)
server = function(input, output) {
user_inputs = reactiveVal(data.frame(title = character(0),
director = character(0),
year = integer(0)))
row_id = 1
observeEvent(
eventExpr = input$new_row,
handlerExpr = {
new_row = add_formGroup(paste0("row", row_id), user_inputs)
insertUI(new_row, selector = "#placeholder", where = "beforeBegin")
row_id <<- row_id + 1
}
)
output$user_inputs = renderTable(user_inputs())
}
add_formGroup = function(id, user_inputs){
moduleServer(id, function(input, output, session){
ns = NS(id)
# Build UI
ui = div(
id = id,
fluidRow(
column(4, textInput(ns("title"), label = NULL, width = "100%")),
column(4, textInput(ns("director"), label = NULL, width = "100%")),
column(3, textInput(ns("year"), label = NULL, width = "100%")),
column(1, actionButton(inputId = ns("remove_entry"), label = "X", style = "margin: 0px; padding: 0px; width: 34px; height: 34px"))
)
)
# Observer for textInputs --> update 'user_inputs' reactiveVal
observeEvent(
eventExpr = {
input$title
input$director
input$year
},
handlerExpr = {
new_row = c(title = input$title, director = input$director, year = input$year)
inputs_df = isolate(user_inputs())
inputs_df[id,] = new_row
user_inputs(inputs_df)
}
)
# Observer for 'remove_entry' --> remove UI
observeEvent(
eventExpr = input$remove_entry,
handlerExpr = {
inputs_df = isolate(user_inputs())
user_inputs(inputs_df[rownames(inputs_df) != id,])
removeUI(selector = paste0("#", id), session = session)
}
)
return(ui)
})
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment