Getting started with modularizing in R Shiny using namespaces can be a bit challenging at first. In the code below, split into "Core App Code" and "Module Code", the reactive object `iris1` is passed between these sections for use across different functions. The code incorporates parameters in the module server function calls and their definitions. It involves assigning the return value from one module to a reactive in the main server function and then passing that reactive to the second module via its server function.
Everything seems to be working fine except for the custom header (a secondary header styled in CSS within the `myContainer` function in the Module Code) that should span multiple columns above the DT table headers but isn't functioning properly. Can you spot what I might be doing wrong?
Code App Code:
library(shiny)
library(DT)
source("C:/Users/.../my_module.R")
ui <- fluidPage(
numericInput("number", label = "Enter sepal length multiplier:", value = 1),
DTOutput('tbl')
)
server <- function(input, output) {
iris1 <- reactive({
tmp <- iris
tmp$Sepal.Length <- tmp$Sepal.Length * input$number
tmp
})
output$tbl <- renderDT({renderTable(iris1())})
# Pass the reactive object iris1 to the module server function
callModule(my_module_server, "myModule", iris1 = iris1)
}
shinyApp(ui, server)
Module Code (saved as my_module.R):
myContainer <- function() {
htmltools::withTags(table(
class = 'display',
thead(
tr(
th(style = "border-top: none;border-bottom: none;"),
th(colspan = 4, 'Lengths and widths',
class = "dt-center",
style = "border-right: solid 0.5px;border-left: solid 0.5px;border-top: solid 0.5px; background-color:#E6E6E6;"
)
),
tr(
th(),
lapply(names(iris1()), th) # Access iris1 reactive object
)
)
))
}
renderTable <- function(data) {
datatable(
data,
container = myContainer(),
options = list(lengthChange = FALSE)
)
}
my_module_ui <- function(id) {
ns <- NS(id)
DTOutput(ns("tbl"))
}
my_module_server <- function(input, output, session, iris1) {
output$tbl <- renderDT({
renderTable(
iris1() # Access iris1 reactive object
)
})
}