if(interactive()){
library(shiny)
# Simple example
ui <- fluidPage(
uiOutput("someui")
)
server <- function(input, output, session) {
output$someui <- renderUI({
# we update the text of new rendered text input to 3 random letters
# after `textInput` is displayed, and it only works for one time.
onNextInput({
updateTextInput(inputId = "mytext", value = paste0(sample(letters, 3), collapse = ""))
})
textInput("mytext", "some text")
})
# if you directly have update event like following line, it won't work
# updateTextInput(inputId = "mytext", value = paste0(sample(letters, 3), collapse = ""))
}
shinyApp(ui, server)
# complex example with modules
modUI <- function(id) {
ns <- NS(id)
textInput(ns("mytext"), "some text")
}
modServer = function(id) {
moduleServer(
id,
function(input, output, session) {
updateTextInput(inputId = "mytext", value = paste0(sample(letters, 3), collapse = ""))
}
)
}
ui = fluidPage(
actionButton("a", "load module UI"),
uiOutput("mod_container")
)
server = function(input, output, session) {
# everytime you click, render a new module UI and update the text value
# immediately
observeEvent(input$a, {
output$mod_container <- renderUI({
onNextInput(modServer("mod"))
modUI("mod")
})
})
# Without `onNextInput`, module server call will not work
# uncomment below and, comment `onNextInput` line to see the difference
# modServer("mod")
}
shinyApp(ui, server)
}
Run the code above in your browser using DataLab