R shiny modularizing

26 Views Asked by At

I'm not seeing the text from the dynamicUIModule in the output. What's wrong with my modularized Shiny app?

    library(shiny)

dynamicUIModule <- function(input, output, session) {
  output$dynamic_ui <- renderUI({
    h3("This is a test!")
  })
}

# Main UI
ui <- fluidPage(
  numericInput("num_input", "Enter a number:", value = 1),
  uiOutput("dynamic_ui"),  # This will display content from serverOnlyModule
  textOutput("display_num")
)

# Main Server
server <- function(input, output, session) {
  
  # Calling the server-only module
  callModule(dynamicUIModule, "dynamic1")
  
  # Other server logic
  output$display_num <- renderText({
    paste0("Squared value: ", input$num_input^2)
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

0
Abbas On

I found the problem. I should have added the UI module as well. For example:

library(shiny)


sidebarUI <- function(id) {
  ns <- NS(id)
  tagList(
    uiOutput(ns("dynamic_ui"))
  )
}

dynamicUIModule <- function(input, output, session, squaredValue) {
  output$dynamic_ui <- renderUI({
    if (squaredValue() > 10) {
      sliderInput(session$ns("dynamic_slider"), "Value is large! Adjust:", min = 1, max = 100, value = 50)
    } else {
      h3("Value is small!")
    }
  })
}


library(shiny)

# Source the module

# Main UI
ui <- fluidPage(
  numericInput("num_input", "Enter a number:", value = 1),
  sidebarUI("dynamic1"),  # This ID should match the ID in renderUI of the module
  textOutput("display_num")
)

# Main Server
server <- function(input, output, session) {
  
  squaredValue <- reactive({
    input$num_input^2
  })
  
  # Calling the dynamic UI module
  callModule(dynamicUIModule, "dynamic1", squaredValue = squaredValue)
  
  # Using the squared value in the main server logic
  output$display_num <- renderText({
    
    paste0("Squared value: ", squaredValue())
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)