首页 > 解决方案 > Alert / notification in shiny

问题描述

I would like to have an alert / notification in shiny app, when user click on download button ! All the examples just work if you have an action button like :

library(shiny)
library(shinyalert)
 
ui <- fluidPage(
   useShinyalert(),  # Set up shinyalert
   actionButton("preview", "Preview")
 )
 
 server <- function(input, output, session) {
   observeEvent(input$preview, {
     # Show a modal when the button is pressed
     shinyalert("Oops!", "Something went wrong.", type = "error")
   })
 }
 
 shinyApp(ui, server)

I want to design similar concept for download button and if we have a download button, then there is no input$preview because I assume for downloadButton we have output$preview and that does not work with current setup !

标签: rshinydownloadnotificationsalert

解决方案


So for a more comprehensive example of how you can use this popup to confirm the download, you can do the following:

  1. We create another actionbutton based on examples here
  2. We are going to hide the original downloadButton using the style = "visibility: hidden;"
  3. We shall listen to the download event via document.getElementById('downloadData').click();
  4. We are going to create a reactiveValues variable to see if the users want to download the data or not
  5. Finally, we need to reset the response so you can click on the Ok button in the popup continuously, otherwise it will not trigger again as it is set to TRUE

library(shiny)
library(shinyalert)

ui <- fluidPage(
    shinyjs::useShinyjs(),
    useShinyalert(), 
    actionButton("init", "Download", icon = icon("download")),
    downloadButton("downloadData", "Download", style = "visibility: hidden;")
)

server <- function(input, output, session) {

    global <- reactiveValues(response = FALSE)
    
    observeEvent(input$init,{
        shinyalert("Confirmation", 
                   "Do you want to download the data?", 
                   type = "success",
                   callbackR = function(x) {
                       global$response <- x
                   },
                   showCancelButton = TRUE
        )
    })
    
    observeEvent(global$response,{
        if(global$response){
            shinyjs::runjs("document.getElementById('downloadData').click();")
            global$response <- FALSE
        }
    })
    
    output$downloadData <- downloadHandler(
        filename = function() {
            paste("data-", Sys.Date(), ".csv", sep="")
        },
        content = function(file) {
            write.csv(mtcars, file)
        }
    )
}

shinyApp(ui, server)

enter image description here


推荐阅读