r - 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 !
解决方案
So for a more comprehensive example of how you can use this popup to confirm the download, you can do the following:
- We create another actionbutton based on examples here
- We are going to hide the original
downloadButton
using thestyle = "visibility: hidden;"
- We shall listen to the download event via
document.getElementById('downloadData').click();
- We are going to create a
reactiveValues
variable to see if the users want to download the data or not - 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 toTRUE
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)
推荐阅读
- python - numpy 数组形状更改/扩展
- javascript - AJAX 提交后 HTML 表单重置
- docker - Traefik 2.2 无法通过 TCP 连接到 Docker Swarm API
- typescript - 使用带有泛型的 keyof 枚举的打字稿
- reactjs - 在 ReactJS 中使用“翻译”属性
- javascript - 固定透明元素不应包含文本而仅包含背景
- swiftui - 是否可以在 SwiftUI 中更改警报的色调?
- python - 如果灰度值在没有列表的列表中,则将所有灰度图像像素更改为白色
- php - 不需要的 PHP 数组键名截断
- oracle - 从 SP 中删除无法正常工作 - Oracle