Reputation: 433
In a shiny app, I have 2 modules, in the first one (mod_1_ui) I have filters and an actionButton.
On the module 2, I want to display a plot WHEN button is clicked.
My problem is that, the observeEvent is in module 2 and the button in module 1.
How can I observeEvent an action in 2 differents modules ?
Below is a reproducible example :
mod_1_ui = function(id) {
ns = NS(id)
fluidRow(
column(
width = 3,
radioButtons(
ns("dist"),
"Distribution type:",
c(
"Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp"
)
),
actionButton(
inputId = ns("btn_go"),
label = "Go !",
icon = icon("play")
)
),
column(width = 9,
mod_2_ui(ns("display_plot"))
)
)
}
mod_1_server = function(id, r_global) {
moduleServer(id, function(input, output, session) {
mod_2_server("display_plot")
})
}
mod_2_ui = function(id) {
ns = NS(id)
plotOutput(outputId = ns("plot"))
}
mod_2_server = function(id, r_global) {
moduleServer(id, function(input, output, session) {
observeEvent(input$btn_go,{
output$plot <- renderPlot({
plot(mtcars$mpg)
})
})
})
}
ui <- fluidPage(
mod_1_ui("mod")
)
server <- function(input, output, session) {
r_global <- reactiveValues()
mod_1_server("mod", r_global = r_global)
}
if (interactive())
shinyApp(ui, server)
Upvotes: 0
Views: 53
Reputation: 125697
One option would be to use a reactive
or a reactiveVal
to pass the state of your button as an argument to the module 2 server:
library(shiny)
mod_1_ui <- function(id) {
ns <- NS(id)
fluidRow(
column(
width = 3,
radioButtons(
ns("dist"),
"Distribution type:",
c(
"Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp"
)
),
actionButton(
inputId = ns("btn_go"),
label = "Go !",
icon = icon("play")
)
),
column(
width = 9,
mod_2_ui(ns("display_plot"))
)
)
}
mod_1_server <- function(id, r_global) {
moduleServer(id, function(input, output, session) {
show <- reactive({
input$btn_go
})
mod_2_server("display_plot", show = show)
})
}
mod_2_ui <- function(id) {
ns <- NS(id)
plotOutput(outputId = ns("plot"))
}
mod_2_server = function(id, r_global, show) {
moduleServer(id, function(input, output, session) {
observeEvent(show(),{
output$plot <- renderPlot({
plot(runif(10, runif(10)))
})
})
})
}
ui <- fluidPage(
mod_1_ui("mod")
)
server <- function(input, output, session) {
r_global <- reactiveValues()
mod_1_server("mod", r_global = r_global)
}
if (interactive()) {
shinyApp(ui, server)
}
Upvotes: 1