johnny
johnny

Reputation: 631

Piping a global input into a Shiny module

Suppose I have the following Shiny module, which doesn't work as I intend:

library(shiny)

# module
module_ui <- function(id) {
  ns <- NS(id)
  uiOutput(ns("choose"))
}
module_server <- function(input, output, session) {
  output$choose <- renderUI({
    selectInput(inputId = "option", 
                label = "choose your option",
                choices = c("a", "b", input$entered_text))
  })
}
# ui and server
ui <- fluidPage(
  textInput("entered_text", label = "Enter a custom option:"),
  module_ui("xyz")
)
server <- function(input, output, session) {
  callModule(module_server, "xyz")
}
shinyApp(ui, server)

How can I pipe the global input, input$entered_text (Line 10), into the module so that the text that the user entered shows up as a choice on the selectInput UI?

I think I am supposed to use reactive(), but I must be doing something wrong.

Upvotes: 2

Views: 679

Answers (2)

colej1390
colej1390

Reputation: 372

callModule() was softly deprecated in Shiny 1.5.0 in favor of moduleServer(). Here is an updated version of @Bas's answer:

library(shiny)

# module
module_ui <- function(id) {
  ns <- NS(id)
  uiOutput(ns("choose"))
}
# ui and server
ui <- fluidPage(
  textInput("entered_text", label = "Enter a custom option:"),
  module_ui("xyz")
)
server <- function(input, output, session, et) {
  et <- reactive(input$entered_text)
  moduleServer(
    "xyz",
    function(input, output, session) {
    output$choose <- renderUI({
      selectInput(inputId = "option", 
                  label = "choose your option",
                  choices = c("a", "b", et()))
    })
  })
}
shinyApp(ui, server)

Upvotes: 1

Bas
Bas

Reputation: 4658

Indeed, you are supposed to use reactive() and pass the result of the entered_text to your module, as such:

library(shiny)

# module
module_ui <- function(id) {
  ns <- NS(id)
  uiOutput(ns("choose"))
}
module_server <- function(input, output, session, et) {
  output$choose <- renderUI({
    selectInput(inputId = "option", 
                label = "choose your option",
                choices = c("a", "b", et()))
  })
}
# ui and server
ui <- fluidPage(
  textInput("entered_text", label = "Enter a custom option:"),
  module_ui("xyz")
)
server <- function(input, output, session) {
  et <- reactive(input$entered_text)
  callModule(module_server, "xyz", et)
}
shinyApp(ui, server)

Upvotes: 1

Related Questions