I am trying to understand the concept of shiny modules. I am attempting to modularize this very simple shinydashboard
app:
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(uiOutput("box"))
)
server <- function(input, output, session) {
output$box <- renderValueBox({
valueBox(
subtitle = "Hi",
value = 2
)
})
}
shinyApp(ui, server)
which works as desired.
However, when modularizing I keep getting the following mistake:
Error in shiny::NS(id) : argument "id" is missing, with no default
.
#### Modules ####
costumizedValueBox <- function(id) {
ns <- shiny::NS(id)
uiOutput(ns("box"))
}
costumizedValueBoxServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
output$box <- renderValueBox({
valueBox(
subtitle = "Hi",
value = 2
)
})
}
)
}
#### App ####
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(costumizedValueBox())
)
server <- function(input, output, session) {
costumizedValueBoxServer()
}
shinyApp(ui, server)
I have tried different modifications of the modularized code, none of which worked, e. g. changing the output (to textOutput
) or the general setup. The error message suggests a problem with the NS
function but I am not able to figure it out.
Thanks!
CodePudding user response:
Modules (i.e., costumizedValueBoxServer and costumizedValueBox) are functions with a required argument.
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(costumizedValueBox("my_id")) # pass in an ID
)
server <- function(input, output, session) {
costumizedValueBoxServer("my_id") # pass in the same ID
}
CodePudding user response:
This is what @Limey describes in the comments: To learn in detail see here https://shiny.rstudio.com/articles/modules.html
library(shiny)
#### Modules ####
costumizedValueBox <- function(id, label = "ValueBox_custom") {
ns <- shiny::NS(id)
uiOutput(ns("box"))
}
costumizedValueBoxServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
output$box <- renderValueBox({
valueBox(
subtitle = "Hi",
value = 2
)
})
}
)
}
#### App ####
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(costumizedValueBox("ValueBox_custom1"))
)
server <- function(input, output, session) {
costumizedValueBoxServer("ValueBox_custom1")
}
shinyApp(ui, server)