Skip to content

Instantly share code, notes, and snippets.

@tbadams45
Last active June 28, 2023 18:25
Show Gist options
  • Save tbadams45/38f1f56e0f2d7ced3507ef11b0a2fdce to your computer and use it in GitHub Desktop.
Save tbadams45/38f1f56e0f2d7ced3507ef11b0a2fdce to your computer and use it in GitHub Desktop.
How to use renderUI in shiny modules. Main takeaway: session$ns("id"). This works in nested modules, too. See the section on session$ns in the documentation for more information: http://shiny.rstudio.com/reference/shiny/latest/session.html
library(shiny)
library(dplyr)
library(ggplot2)
innerModUI <- function(id) {
ns <- NS(id)
fluidPage(fluidRow(
uiOutput(ns("inner_slider")),
plotOutput(ns("inner_plot"))
))
}
innerMod <- function(input, output, session) {
output$inner_slider <- renderUI({
sliderInput(session$ns("slider2"), label = "inner module slider", min = round(min(mtcars$mpg)),
max = round(max(mtcars$mpg)), value = c(min(mtcars$mpg), max(mtcars$mpg), step = 1))
})
output$inner_plot <- renderPlot({
req(input$slider2)
data <- filter(mtcars, between(mpg, input$slider2[1], input$slider2[2]))
ggplot(data, aes(mpg, wt)) + geom_point()
})
}
outerModUI <- function(id) {
ns <- NS(id)
fluidPage(fluidRow(
uiOutput(ns("outer_slider")),
plotOutput(ns("outer_plot")),
innerModUI(ns("inner"))
))
}
outerMod <- function(input, output, session) {
callModule(innerMod, "inner")
output$outer_slider <- renderUI({
sliderInput(session$ns("slider1"), label = "outer module slider", min = round(min(mtcars$mpg)),
max = round(max(mtcars$mpg)), value = c(min(mtcars$mpg), max(mtcars$mpg), step = 1))
})
output$outer_plot <- renderPlot({
req(input$slider1)
data <- filter(mtcars, between(mpg, input$slider1[1], input$slider1[2]))
ggplot(data, aes(mpg, wt)) + geom_point()
})
}
ui <- fluidPage(
fluidRow(
outerModUI("outer")
)
)
server <- function(input, output, session) {
callModule(outerMod, "outer")
}
shinyApp(ui = ui, server = server)
@JGWestie
Copy link

Thanks so much for this example, it helped me figure out how to resolve a complex nested module problem I was having.

I believe the error message generated in the example is due to incorrect bracket placement in the sliderinput lines of code.

This line (appears twice in the example):
value = c(min(mtcars$mpg), max(mtcars$mpg), step = 1))

Should be this:
value = c(min(mtcars$mpg), max(mtcars$mpg)), step = 1)

@idavydov
Copy link

session$ns("id") is a life saver, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment