DT collapse all row groups by default

I am trying to make all row groups in a datatable collapse by default, with the below code, the DTs did collapsed at first, however when navigate back & forth, the 1st table unintentionally expanded.

my current implementation:

library(shiny)
library(DT)
ui <- fluidPage(# Application title
  titlePanel("Collapse/Expand table"),
  mainPanel(
    tabsetPanel(
      tabPanel("table1", dataTableOutput("my_table")),
      tabPanel("table2", dataTableOutput("my_table2"))
    )
  ))

callback_js <- JS(
  "table.on('click', 'tr.dtrg-group', function () {",
  "  var rowsCollapse = $(this).nextUntil('.dtrg-group');",
  "  $(rowsCollapse).toggleClass('hidden');",
  "});",
  "table.on('init', () => $('.dtrg-group').trigger('click'))"
)

server <- function(input, output) {
  output$my_table <- DT::renderDataTable({
    datatable(
      mtcars[1:15, 1:5],
      extensions = 'RowGroup',
      options = list(rowGroup = list(dataSrc = 3), pageLength = 20),
      callback = callback_js,
      selection = 'none'
    )
  })
  
  output$my_table2 <- DT::renderDataTable({
    datatable(
      mtcars[1:15, 1:5],
      extensions = 'RowGroup',
      options = list(rowGroup = list(dataSrc = 3), pageLength = 20),
      callback = callback_js,
      selection = 'none'
    )
  })
}

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

My desired output:

All row groups should be collapsed at initial (at 1st time table is rendered), and remain collapsed until user click on it, I cannot found any solutions existed yet

This question was posted on Stackoverflow also

I have figure out the solution with the help of this warm community :smiling_face_with_three_hearts:, the solution is posted here: https://stackoverflow.com/a/66774002/14140854

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.