CallumH
CallumH

Reputation: 779

How to return the filtered rows in a reactable table in a Shiny app module

I am looking for some help please to develop a solution to return the filtered rows in a reactable table in a Shiny app module.

I am looking to identify which rows are the subset of mtcars after the columns have been filtered with free text in the filter fields. The closest solution that I have found is at https://github.com/glin/reactable/issues/104#issuecomment-1262273788, however, I just can’t get it to sing inside a Shiny module.

I have placed calls to the ns() function in the jsCode string where I believe they should be, but can’t get the verbatimTextOutput 'out' element to show which rows, by index, are selected.

Any help would be appreciated. TIA

library(shiny)
library(reactable)
library(shinyjs)

firecastUI <- function(id) {
  ns <- NS(id)
  jsCode <- paste('shinyjs.getSortedData = function() {
  try {
    var idx = Reactable.getInstance("', ns('a_table'),'").sortedFlatRows.map(x => x.index + 1);
    Shiny.onInputChange("', ns('sorted_data'),'", idx);
  } catch {}
}')
  
  tagList(
    useShinyjs(),
    extendShinyjs(text = jsCode, functions = "getSortedData"),
    reactableOutput(ns('a_table')),
    br(),
    verbatimTextOutput(ns("out"))
  )
}

firecastServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      
      output$a_table <- renderReactable({
        reactable(
          data = mtcars,
          filterable = TRUE
        )
      })
      
      observe({
        invalidateLater(100)
        js$getSortedData()
      })
      
      output$out <- renderPrint({
        input$sorted_data
      })
    }
  )
}


ui <- fluidPage(
  firecastUI('fire')
)

server <- function(input, output, session) {
  firecastServer('fire')
}

shinyApp(ui, server)

Upvotes: 0

Views: 330

Answers (0)

Related Questions