Home > Net >  Dyamic input in Shiny modules
Dyamic input in Shiny modules

Time:06-14

I struggle with making a dynamic selectInput() when working with Shiny modules.

I have the following app (without modules):

library(shiny)

ui <- fluidPage(
    numericInput("n", "n", 10),
    uiOutput("select"),
    uiOutput("res")
)

server <- function(input, output, session) {
  output$select <- renderUI(
    selectInput("sample_size", "Sample size", choices = 1:input$n)
  )
  output$res <- renderUI(
    renderPrint(rnorm(input$sample_size))
  )
}

shinyApp(ui, server)

I am not sure how to properly use namespaces when modularizing this app. My current attempt looks like this:

library(shiny)

sampleUI <- function(id){
  ns <- NS(id)
  fluidPage(
    numericInput("n", "n", 10),
    uiOutput(ns("select")), 
    uiOutput("res")
  )
}

sampleServer <- function(input, output, session) {
  output$select <- renderUI(
    selectInput("sample-size", "Sample size", choices = 1:input$n)
  )
  output$res <- renderUI(
    renderPrint(rnorm(input$sample_size))
  )
}

ui <- fluidPage(
  sampleUI("mod1")
)

server <- function(input, output, session) {
  callModule(sampleServer, "mod1")
}

shinyApp(ui, server)

CodePudding user response:

When making new IDs in the server module, always use session$ns around the ID. This is the case here for your selectInput. Also fixed a typo, and an ns() in the UI function:

library(shiny)

sampleUI <- function(id){
  ns <- NS(id)
  fluidPage(
    numericInput(ns("n"), "n", 10),
    uiOutput(ns("select")), 
    uiOutput("res")
  )
}

sampleServer <- function(input, output, session) {
  output$select <- renderUI(
    selectInput(session$ns("sample_size"), "Sample size", choices = 1:input$n)
  )
  output$res <- renderUI(
    renderPrint(rnorm(input$sample_size))
  )
}

ui <- fluidPage(
  sampleUI("mod1")
)

server <- function(input, output, session) {
  callModule(sampleServer, "mod1")
}

shinyApp(ui, server)
  • Related