Skip to content

Instantly share code, notes, and snippets.

@ColinFay
Created May 10, 2019 17:55
Show Gist options
  • Select an option

  • Save ColinFay/e70c839e14dd58177c37f31e10c0f057 to your computer and use it in GitHub Desktop.

Select an option

Save ColinFay/e70c839e14dd58177c37f31e10c0f057 to your computer and use it in GitHub Desktop.
library(shiny)
# You can put input to both your functions
mod_ui <- function(id, title){
# The ns here is a function that will help to 'namespace' the ids
# In other words, it will turn "go" into "chosennamespace-go"
ns <- NS(id)
tagList(
h2(title),
selectInput(
# with mod_ui("ui1"), it will create an id 'ui1-what'
# with mod_ui("ui2"), it will create an id 'ui2-what'
# So that way I'm sure what happens in ui1 is caught by the
# correct server function
ns("what"),
"What",
choices = c("iris", "mtcars", "airquality")
),
plotOutput(ns("plot"))
)
}
# You can put input to both your function
mod_server <- function(input, output, session){
# I dont' need ns() here, the callModule makes sure
# to par the good ui-namespace with the good server call
output$plot <- renderPlot({
switch(
input$what,
"iris" = plot(iris),
"mtcars" = plot(mtcars),
"airquality" = plot(airquality)
)
})
# Your module can return a value if you want
}
ui <- fluidPage(
column(6, mod_ui("ui1", title = "left")),
column(6, mod_ui("ui2", title = "right"))
)
server <- function(input, output, session) {
# I use the module server function + the ui id it refers to
# When shiny is run, the mod_ui("ui1") is watched by the first
# callModule, "ui2" by the second one
callModule(mod_server, "ui1")
callModule(mod_server, "ui2")
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment