Reputation: 881
I have a button in one module. When I click the button a panel should appear. This panel is placed in another module. I tried to pass button's 'click' action between modules using some reactivity but my code doesn't work properly. Here is a workable example:
library(shiny)
library(shinyjs)
# UI #
mod_btn_UI <- function(id) {
ns <- NS(id)
actionButton(ns("btn"), "Click me!")
}
mod_btn_server <- function(id){
moduleServer(id, function(input, output, session) {
btnPanel <- eventReactive(input$btn,{
return()
})
})
}
mod_body_UI <- function(id) {
ns <- NS(id)
shinyjs::useShinyjs()
shinyjs::hidden(absolutePanel(ns("panel"),
tagList(shinyWidgets::actionBttn(inputId = "XYZ", icon = icon("chart-line")))))
}
# Server #
mod_body_server <- function(id, btnOne){
moduleServer(id, function(input, output, session) {
observeEvent(btnOne(), {
shinyjs::toggle(id = "panel")
})
})
}
# App #
ui <- fluidPage(
shinyjs::useShinyjs(),
tagList(
mod_btn_UI("test-btn"),
mod_body_UI("test-body")
)
)
server <- function(input, output, session) {
btnVal <- mod_btn_server("test-btn")
mod_body_server("test-body", btnOne = btnVal$btnPanel)
}
shinyApp(ui = ui, server = server)
I tried various methods to pass button 'click' to another module but it doesn't work. I also checked this eventReactive in shiny module but in my example I don't want to return value as output, just make some GUI to appear.
Upvotes: 1
Views: 914
Reputation: 21287
Your btn pass is working. Also, shinyjs::toggle
is now working. Try this
library(shiny)
library(shinyjs)
moduleServer <- function(id, module) {
callModule(module, id)
}
# UI #
mod_btn_UI <- function(id) {
ns <- NS(id)
tagList(
actionButton(ns("btn"), "Click me!")
)
}
mod_btn_server <- function(id){
moduleServer(id, function(input, output, session) {
# btnPanel <- eventReactive(input$btn,{
# cars ## return()
# })
b1 <- reactive(input$btn)
})
}
mod_body_UI <- function(id) {
ns <- NS(id)
shinyjs::useShinyjs()
div(id = "advanced" ,
tagList(
shinyjs::hidden(plotOutput(ns("plot2")))
))
}
# Server #
mod_body_server <- function(id, btnOne){
moduleServer(id, function(input, output, session) {
ns <- session$ns
output$plot2 <- renderPlot({hist(rnorm(500))})
observeEvent(btnOne(), {
shinyjs::toggle(id = "plot2") ## toggle is now working
})
})
}
# App #
ui <- fluidPage(
shinyjs::useShinyjs(),
tagList(
mod_btn_UI("test-btn"),
mod_body_UI("test-body")
)
)
server <- function(input, output, session) {
btnVal <- mod_btn_server("test-btn")
#mod_body_server("test-body", btnOne = btnVal$btnPanel)
mod_body_server("test-body", btnVal )
}
shinyApp(ui = ui, server = server)
Upvotes: 2