Search code examples
rshinynested-tablereactable

How to keep track of nested tables in reactable?


I have a problem that I'm not quite sure how to solve. Consider this example Shiny app:

library(shiny)
library(reactable)
library(dplyr)


random_requests <- data.frame(
    Request_ID = c(1,2,3,4,5),
    Status = c("Accepted", "Accepted", "Accepted", "Declined", "Created")
)

random_samples <- data.frame(
    Request_ID = c(1,1,1,2,3,3,4,5),
    Sample_ID = c(1,2,3,4,5,6,7,8),
    statistics = sample(1:100, 8)
)


# Define UI for application 
ui <- fluidPage(
    
   selectInput(inputId = "select",
               label = "Select a choice:",
               choices = c("All", "Accepted", "Declined", "Created")),
    hr(),
    reactableOutput(outputId = "table")
)

# Define server logic 
server <- function(input, output) {
    
    
    data <- eventReactive(input$select, {
        if(input$select == "All"){
            random_requests
        } else {
            random_requests %>%
                filter(Status == input$select)
        }
    })
    
    
    output$table <- renderReactable({
        
        reactable(
            data(),
            details = function(index, name){
                htmltools::div(
                    reactable(random_samples[random_samples$Request_ID == index, ])
                )
            }
            )
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

I'd like to make use of the expandable rows feature of reactable. The main table should show Requests, then when you expand the row, the sub table should show the Samples that are associated with that particular Request. This works fine when the table is static, but when I go to filter using the dropdown it does not behave as intended. The current subtable matches by row index, so when I filter the table, the Sample sub-tables don't match up with the correct Request.

How could I achieve this functionality? That is, how to link the random_requests and random_samples tables by Request_ID inside the details function so that it works when filtering?

Thanks! -Kyle


Solution

  • Answered by package developer Greg Lin: https://github.com/glin/reactable/issues/199#issuecomment-933003834

    This functionality can be achieved by modified the reactable code to:

    output$table <- renderReactable({
        
        reactable(
          data(),
          details = function(index, name){
            request_id <- data()[index, "Request_ID"]
            htmltools::div(
              reactable(random_samples[random_samples$Request_ID == request_id, ])
            )
          }
        )
      })