Chapter 2 Shiny Modules
2.1 Naming the functions
Call the module functions in pairs e.g. * name = func() * nameUI = func()
A module’s UI function should be given a name that is suffixed with Input, Output, or UI; for example, csvFileInput, zoomableChoroplethOutput, or tabOneUI
2.2 UI
- Add id argument
- Add ns = NS(id) Make namespace function
- Wrap all input IDs and output Ids in ns ns(“slider”)
2.3 Server
- Include input, output, session arguments
- Do not use ns() to refer to inputs and outputs from the module
2.4 Using module server
- Call callModule() from insider server()
- 1st argument = module function (no quotes, no brackets)
- 2nd argument = same id as UI
2.5 Loading the functions
- File sourced by global.R
- In a package that the app loads
2.6 Example
sliderTextUI <- function(id){
ns = NS(id)
tagList(
sliderInput(ns("slider"), "Slide me", 0, 100, 1),
textOutput(ns("number"))
)
}
sliderText <- function(input, output, session){
output$number = renderText({
input$slider
})
}
ui = fluidPage(
sliderTextUI("one"),
sliderTextUI("two")
)
server = function(input, output){
callModule(sliderText, "one")
callModule(sliderText, "two")
}
shinyApp(ui, server)
2.7 To return a reactive output from a module
- Return reactive output as a reactive expression (or list of reactive expressions)
- callModule() returns all of the output returned by the server function
2.8 How to pass reactive input to a module?
- Wrap the input as a reactive expression
foo = reactive({rv$foo})
Even is alreadyinput$num
- Pass the reactive expression to the module as an argument e.g. module(data = foo) [No brackets]
- Treat the argument as a reactive expression withint the function (e.g. data())
2.9 Effective use of Shiny Modules
2.9.1 Careful design
- What does the module do?
- What is it trying to accomplish?
- What should I call my module?
2.9.2 Inputs and return values
- Static or reactive inputs?
- Complexity of return values
Which outputs serve as inputs for other modules?
- Document your modules (roxygen2 @param @return)
- When to ()?
- function(input, output, foo)
- foo()
- return(foo)
plot1vars$xvar()
NOT plot1vars2()$xvar