Last active
June 28, 2023 18:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
session$ns("id")
is a life saver, thank you.