langtang
langtang

Reputation: 24722

How to close shiny modal box after clicking on downloadButton

I have an actionButton that, when clicked, opens a modal dialog box that offers a small message, and gives user an opportunity to download data or cancel. When clicking on the download button, the downloadHandler is appropriately triggered, and data downloads successfully. However, I don't know where/how to include removeModal(). I want the pop up modal dialog box to automatically close when the downloadButton is clicked.

library(shiny)
library(data.table)

data = data.frame(x=rnorm(10),y=rnorm(10))

get_download_handler <- function(fname, data) {
  downloadHandler(
    filename = function() paste0(fname, '.csv'),
    content = function(con) data.table::fwrite(data, con)
  )
}

ui <- fluidPage(
  actionButton(inputId = "dwnld",label = "Download Data")  
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title="Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data","Download Data"),
        modalButton("Cancel")
      ),easyClose = TRUE
    ))
  })
  
  output$dwnld_data <-get_download_handler(fname="data",data)
}

shinyApp(ui, server)

Upvotes: 2

Views: 958

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

You can do like this:

library(shiny)
library(data.table)

data = data.frame(x = rnorm(10), y = rnorm(10))

ui <- fluidPage(
  actionButton(inputId = "dwnld", label = "Download Data")  
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title = "Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data", "Download Data"),
        modalButton("Cancel")
      ),
      easyClose = TRUE
    ))
  })
  
  output$dwnld_data <- downloadHandler(
    filename = "data.csv",
    content = function(con){
      on.exit(removeModal())
      data.table::fwrite(data, con)
    }
  )
}

shinyApp(ui, server)

Upvotes: 3

Related Questions