glin / reactable

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

Use js function saved in inst folder on `onClick` #312

Closed jiwanheoJazz closed 1 year ago

jiwanheoJazz commented 1 year ago

Hi, thanks for the awesome package!

Currently, onClick must be "expand", "select", or a JS function.

I'm using reactable in a golem Shiny package. I'm wondering if it's possible to use as onClick argument the string name of a JS function I defined in the inst folder? This would help avoid writing same code in different places of the shiny app

expected behaviour:

JS code (rowColReactable.js in inst/app/www folder):

function rowColReactable(rowInfo, colInfo) {
  if (window.Shiny) {
    Shiny.setInputValue('row', { index: rowInfo.index + 1 })
    Shiny.setInputValue('col', { column: colInfo.id })
  }
}

Shiny code:

output$tbl <- renderReactable({
      reactable::reactable(
        data = head(mtcars, 10),
        onClick = "rowColReactable"
      )
    })
glin commented 1 year ago

Hi, it's not possible to specify a string name for onClick, but you could achieve the same thing using a function that reads and returns that external JS code. For example, you could have a function in your package that reads the file from inst/app/www and returns the code wrapped in JS():

# Read JS file from inst/app/www folder
rowColReactable <- function() {
  file <- system.file("app/www/rowColReactable.js", package = "myPackage", mustWork = TRUE)
  reactable::JS(readLines(file))
}

And then to use it in a table:

reactable::reactable(mtcars, onClick = rowColReactable())
jiwanheoJazz commented 1 year ago

Aha, that works, thank you!