glin / reactable

Interactive data tables for R
https://glin.github.io/reactable
Other
627 stars 80 forks source link

Click Action - Custom Click Action - Not Responsive to Searching #294

Closed sprucemister closed 1 year ago

sprucemister commented 1 year ago

On the example for a Customer Click Action using JS, when combined with searchable = TRUE, the show_details object will return an incorrect row index if a search term is entered

glin commented 1 year ago

I can't reproduce this when I add searching to that example, and filter down the table with something like "BMW". Can you provide more details on what you searched for and what row index you got?

Here's my example code:

library(reactable)

data <- cbind(
  MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "Price")],
  details = NA
)

reactable(
  data,
  searchable = TRUE,
  columns = list(
    # Render a "show details" button in the last column of the table.
    # This button won't do anything by itself, but will trigger the custom
    # click action on the column.
    details = colDef(
      name = "",
      sortable = FALSE,
      cell = function() htmltools::tags$button("Show details")
    )
  ),
  onClick = JS("function(rowInfo, column) {
    // Only handle click events on the 'details' column
    if (column.id !== 'details') {
      return
    }

    // Display an alert dialog with details for the row
    window.alert('Details for row ' + rowInfo.index + ':\\n' + JSON.stringify(rowInfo.values, null, 2))

    // Send the click event to Shiny, which will be available in input$show_details
    // Note that the row index starts at 0 in JavaScript, so we add 1
    if (window.Shiny) {
      Shiny.setInputValue('show_details', { index: rowInfo.index + 1 }, { priority: 'event' })
    }
  }")
)

When I search for "bmw", the last row, I get the correct row index from the "show details" button: details for custom cell click action example table, filtered by "bmw"

Note: this is the 5th row in the table, but row index 4 because indexes in the JavaScript API start at 0. I also wonder if the zero-indexing difference is what you're seeing too.

sprucemister commented 1 year ago

You're right this is giving the expected, desired output. I was missing a filter I should have had before taking the row number and using it to filter the reactive that populates another table so the user can make a curated list.

Thank you Greg!