Created
January 2, 2019 20:06
-
-
Save strboul/01c942c77a9b57411f200ea8729fac16 to your computer and use it in GitHub Desktop.
Shiny updateTextInput between modules by passing the session object in between
This file contains hidden or 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) | |
# MODULES ---------------------------------------------------------------------- | |
text_ui <- function(id) { | |
ns <- shiny::NS(id) | |
shiny::tagList( | |
textInput(ns("text"), "Write here"), | |
verbatimTextOutput(ns("display")) | |
) | |
} | |
text_server <- function(input, output, session) { | |
rv.text <- reactiveValues(val = FALSE) | |
observeEvent(input$text, { | |
rv.text$val <- input$text | |
}) | |
output$display <- renderText({ | |
rv.text$val | |
}) | |
return({ session }) | |
} | |
reset_btn_ui <- function(id) { | |
ns <- shiny::NS(id) | |
shiny::tagList( | |
actionButton(ns("reset"), "Reset") | |
) | |
} | |
reset_btn_server <- function(input, output, session, TextModuleSession) { | |
observeEvent(input$reset, { | |
updateTextInput(session = TextModuleSession, "text", value = "") | |
}) | |
} | |
# MAIN ------------------------------------------------------------------------- | |
ui <- fluidPage( | |
fluidRow( | |
column(6, | |
text_ui("text"), | |
reset_btn_ui("btn") | |
) | |
) | |
) | |
server <- function(input, output, session) { | |
TextModuleSession <- callModule(module = text_server, | |
id = "text") | |
callModule(module = reset_btn_server, | |
id = "btn", | |
TextModuleSession) | |
} | |
# Shiny update and reset input with Shiny modules | |
# Related source: https://stackoverflow.com/a/51757792/ | |
shinyApp(ui, server) |
Nice! Helped me solving a tidy bit different example, where an actionButton inside a module should trigger an action outside of the module. Passing the mainSession object inside the module worked:
mod_module1_server("module1_1", mainSession = session)
and then in the module e.g. updating the currently selected tab of a tabsetPanel by using an actionButton within the module UI worked like this:
observeEvent(input$actionButton1, { updateTabItems(session = mainSession, inputId = "sidebarMenu", selected = "tab1") })
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for this example, passing 'TextModuleSession' is very useful !