I am trying to modularize an existing single file application. I tried to check existing answers in this topic, but still not able to get my demo code to work. I guess I am close to the working solution but there is something I still missing or misused.
library(shiny)
uiModule <- function(id) {
ns <- NS(id)
sidebarPanel(
actionButton(inputId = "actBtn1", label = "do"),
actionButton(inputId = "actBtn2", label = "do2")
)
}
srvModule <- function(input, output, session) {
ns <- session$ns
observeEvent(ignoreInit = TRUE, ns(input$actBtn1) , {
message("clicked 111")
})
observeEvent(ignoreInit = TRUE, ns(input$actBtn2) , {
message("clicked 222")
})
}
serverMain <- function(input, output, session) {
output$menu <- renderMenu({
sidebarMenu(menuItem(
"Menu item",
tabName = "dashboard",
icon = icon("calendar")
))
})
moduleServer( id = "myMod", module = srvModule, session = session)
}
uiMain <- dashboardPage(
dashboardHeader(title = "Mysidebar"),
dashboardSidebar(sidebarMenu(id = "mytabs", sidebarMenuOutput("menu"))),
dashboardBody(tabItems(tabItem(
tabName = "dashboard", h2("Dashboard tab content")
)), uiModule("myModuleUI"))
)
shinyApp(uiMain, serverMain)
What can I try next?
3
There are a few changes to your approach that I would recommend
- in
uiModule
, you need to wrap the inputId values withns()
. For example
actionButton(inputID = ns("actBtn1"), ...)
-
the signature for
srvModule
should befunction(id)
, and the function should return the result of amoduleServer()
function. -
Within that
moduleServer()
function you do not need to wrap your references to inputs withns()
. For example, instead of
observeEvent(ignoreInit = TRUE, ns(input$actBtn1), ...)
you need to use
observeEvent(ignoreInit = TRUE, input$actBtn1, ...)
- The
id
value that you pass tosrvModule()
and touiModule()
needs to be the same value (for example"myMod"
).
Here is a full working example:
library(shiny)
library(shinydashboard)
uiModule <- function(id) {
ns <- NS(id)
sidebarPanel(
actionButton(inputId = ns("actBtn1"), label = "do"),
actionButton(inputId = ns("actBtn2"), label = "do2")
)
}
srvModule <- function(id) {
moduleServer(id, function(input, output, session) {
observeEvent(ignoreInit = TRUE, input$actBtn1 , {
message("clicked 111")
})
observeEvent(ignoreInit = TRUE, input$actBtn2 , {
message("clicked 222")
})
})
}
serverMain <- function(input, output, session) {
output$menu <- renderMenu({
sidebarMenu(menuItem(
"Menu item",
tabName = "dashboard",
icon = icon("calendar")
))
})
srvModule(id = "myMod")
}
uiMain <- dashboardPage(
dashboardHeader(title = "Mysidebar"),
dashboardSidebar(sidebarMenu(id = "mytabs", sidebarMenuOutput("menu"))),
dashboardBody(tabItems(tabItem(
tabName = "dashboard", h2("Dashboard tab content")
)), uiModule(id = "myMod"))
)
shinyApp(uiMain, serverMain)
3