rshinydtsweetalertsweetalert2

Use SweetAlert2 in R Shiny


I am trying to use SweetAlert2 pop ups instead of traditional JS pop ups. Looking forward to an example to achieve the same as I am new to JS Concepts. Visit -https://sweetalert2.github.io/ In actual Scenario, I would like to use these SweetAlert2 instead JS Alerts on double click of Data Table Row.

Code with JS Popup:

library(shiny)
library(shinydashboard)
library(DT)

ui <- shinyUI(

dashboardPage (
    dashboardHeader(title="Report"),
    dashboardSidebar(sidebarMenu(menuItem("Table",tabName="Table"))),
    dashboardBody(      
        tabItems(
        tabItem(tabName = "Table",
            DT::dataTableOutput("DataTable")    
        )
   ))

))

server <- shinyServer(function(input, output) {
     output$DataTable <- DT::renderDataTable({
          datatable(iris,rownames=FALSE,selection = 'single',
                    options = list(
                              searching = FALSE,ordering=FALSE,
                              dom = 'Bfrtip',
                              buttons = c('copy','excel', 'pdf', 'print', 'colvis'),
                              columnDefs = list(list(visible=FALSE, targets=c(2))
          ),
     rowCallback = JS(
          "function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {",
          "var full_text = aData[2]",
          # Tooltip for the rows
          "$('td:eq(1)', nRow).attr('title', full_text);",
          # Showing a hand as a cursor
          "$('td:eq(1)', nRow).css('cursor','pointer');",
          "$('td:eq(1)', nRow).css('font-weight','bold');",
          "}")
      ),
      #On double Click show Alert Message
     callback = JS('
          table.on("dblclick.dt","tr", function() {
          var data=table.row(this).data();
          alert("You clicked on "+data[4]+"\'s row");})
          '))
})
})

shinyApp(ui,server)

Solution

  • I'm not familiar with that JS library, anyway this is what I think should work.

    ui.R

    First you have to add the js script to you page (pay attention to the path, it should be either a CDN or a file inside the /www/ folder:

    tags$head(HTML("<script type='text/javascript' src='path/to/sweetAlert2.js'></script>"))
    

    server.R

    Then in you callback you can call the library function:

    callback = JS('
        table.on("dblclick.dt","tr", function() {
            var data=table.row(this).data();
            swal({
                title: "Click!",
                text: "You clicked on "+data[4]+"\'s row",
                type: "success",
                confirmButtonText: "Cool"
            })
        )')
    

    Hope this helps