Skip to content

Instantly share code, notes, and snippets.

@cecilialee
Last active February 14, 2018 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilialee/3df086e4605d7723eb315761a9c2127d to your computer and use it in GitHub Desktop.
Save cecilialee/3df086e4605d7723eb315761a9c2127d to your computer and use it in GitHub Desktop.
Simple module in Shiny. #r #shiny
# UI ==========================================================================
textModalInput = function(id) {
ns <- NS(id)
tagList(
textInput(ns("txt"), "Write something")
)
}
# Server ======================================================================
textModalServer = function(input, output, session) {
mytext <- reactive({
input$txt
})
return(mytext)
}
# UI ==========================================================================
confirmModalInput = function(id) {
ns <- NS(id)
tagList(
actionButton(ns("show"), "Show modal dialog"),
verbatimTextOutput(ns("print"))
)
}
# Server ======================================================================
confirmModalServer = function(input, output, session) {
ns <- session$ns
# Create object to store reactive values
vals <- reactiveValues(
txt = NULL,
error_msg = NULL,
print = FALSE
)
# Create modal
popupModal <- function() {
modalDialog(
textInput(ns("txt"), "Write something"),
textOutput(ns("skip_error_msg")),
footer = tagList(
modalButton("Cancel"),
actionButton(ns("ok"), "OK")
)
)
}
# Show modal when button is clicked
observeEvent(input$show, {
vals$error_msg <- NULL
showModal(popupModal())
})
# Validate submission
observeEvent(input$ok, {
vals$txt <- input$txt
if (!is.null(vals$txt) && nzchar(vals$txt)) {
removeModal()
vals$print <- TRUE
} else {
vals$error_msg <- "You did not input anything."
}
})
# Output error message
output$skip_error_msg <- renderText({
vals$error_msg
})
# Output inputted text
output$print <- renderPrint({
if (vals$print) {
vals$txt
} else {
NULL
}
})
}
library(shiny)
source("modules/module_1.R")
source("modules/module_2.R")
ui = basicPage(
# module 1
strong("Module 1", style = "color:steelblue;"),
textModalInput("txt_modal"),
textOutput("txt"),
# module 2
strong("Module 2", style = "color:steelblue;"),
br(),
confirmModalInput("confirm_modal")
)
server = function(input, output, session) {
# module 1
confirm_txt <- callModule(textModalServer, "txt_modal")
output$txt <- renderText({
confirm_txt()
})
# module 2
callModule(confirmModalServer, "confirm_modal")
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment