0

Using rhandsontable in a Shiny app, I want to detect when the user deselects a row. In this example, when I click a row, I can detect the selection with input$mytable_select$select$r, but when I click outside the table, input$mytable_select$select$r is still set to the row number even though the row is no longer highlighted. I could create a button and when the user clicks it, reload the rhandsontable, but I would prefer not to do this.

require(shiny)
require(rhandsontable)
shinyApp(
  ui = fluidPage(
    rHandsontableOutput("mytable")
  ),
  server = function(input, output, session) {

    output$mytable <- renderRHandsontable({
      rhandsontable(
        data = mtcars,
        selectCallback = T
      )
    })
    
    observe({
      if(is.null(input$mytable_select$select$r)) {
        print("No rows selected")
      } else {
        print(paste0("Selected row: ", input$mytable_select$select$r))
      }
    })  
  
  }
)
mat
  • 2,412
  • 5
  • 31
  • 69
Ben Ernest
  • 445
  • 3
  • 14

1 Answers1

0

I found a solution from reading a handsontable issue discussion (https://github.com/handsontable/handsontable/issues/902). I can pass a javascript function to a parameter 'afterDeselect' which sets input$mytable_select to NULL after the table is deselected. Alternatively, I could modify the javascript function to use Math.random() to set a Shiny input value to a new random number after the table is deselected and use observeEvent() to listen for changes to the input value.

require(shiny)
require(rhandsontable)
shinyApp(
  ui = fluidPage(
    rHandsontableOutput("mytable")
  ),
  server = function(input, output, session) {
    
    output$mytable <- renderRHandsontable({
      rhandsontable(
        data = mtcars,
        selectCallback = T,
        afterDeselect = htmlwidgets::JS(
          "function() {Shiny.onInputChange('mytable_select', null)}"
        )
      )
    })
    
    observe({
      if(is.null(input$mytable_select$select$r)) {
        print("No rows selected")
      } else {
        print(paste0("Selected row: ", input$mytable_select$select$r))
      }
    })
    
  }
)
Ben Ernest
  • 445
  • 3
  • 14