DJC
DJC

Reputation: 1611

Passing a reactive value into a called module

I have a simple app which utilizes a module to display some text. When I call the module in my app, I would like to pass a reactive value from the map into the module for rendering, but for some reason this is not working. Can anybody tell me what is wrong with my code?

Also, I recognize similiar questions have been asked before, but most answers I see use callModule which has been deprecated in favor of moduleServer.

## libraries
library(tidyverse)
library(shiny)
library(plotly)

## create module to print text - not that UI selector must be rendered from server as this is behavior in real app
textUI <- function(id) {
  uiOutput(NS(id, "UI"))
}

textServer <- function(id, message_text) {
  moduleServer(id, function(input, output, session) {
    output$UI <- renderUI({
      textOutput(outputId = NS(id, "text"))
    })
    output$text <- renderText(expr = message_text)
  })
}

## call module components
ui <- fluidPage(
  selectInput(inputId = "message", 
              label = "Text Display", 
              choices = c("a", "b")),
  textUI(id = "test")
)

server <- function(input, output, session) {
  textServer(id = "test", 
             message_text = input$message)
}

shinyApp(ui, server)

Edit: text code for clarity

Upvotes: 0

Views: 88

Answers (1)

Geovany
Geovany

Reputation: 5687

The input parameter should be sent as reactive, for that just use reactive(input$message). Since now message_text is a reactive value, you need to use it as message_text().

library(shiny)

## create module to print text - not that UI selector must be rendered 
## from server as this is behavior in real app
textUI <- function(id) {
  uiOutput(NS(id, "UI"))
}

textServer <- function(id, message_text) {
  moduleServer(id, function(input, output, session) {
    output$UI <- renderUI({
      textOutput(outputId = NS(id, "text"))
    })
    output$text <- renderText(expr = message_text())
  })
}

## call module components
ui <- fluidPage(
  selectInput(inputId = "message", 
              label = "Text Display", 
              choices = c("a", "b")),
  textUI(id = "test")
)

server <- function(input, output, session) {
  textServer(id = "test", 
             message_text = reactive(input$message))
}

shinyApp(ui, server)

Upvotes: 2

Related Questions