admin管理员组

文章数量:1122832

An issue that I keep running into quite frequently is that I need to perform proxy actions on a DT table in a shiny app before it ever becomes visible. This is usually when the table is in a conditional panel whose condition has never been true, or if the table is in a tab within a tabsetPanel that has never been active.

Interestingly, the replaceData action will work if it is run before the table is ever rendered, and when it is rendered it will show the correct data, but most, if not all other proxy actions will not work until the table has been rendered first.

Here is a demo app. The table is on the second tab and will not render until the second tab is activated. On the first tab are two buttons. The "Select 1st Row" button will select the first row of the table. If that button is clicked before ever activating the second tab, the first row will not be selected when going to the second tab. If it is clicked after activating the second tab, it will be selected. The "Replace Data" button will replace the data in the table, and that does work if clicked before ever activating the second tab.

library(shiny)
library(DT)

ui <- fluidPage(
  tabsetPanel(
    id = "tabs",
    tabPanel("Tab 1",
             actionButton("select", "Select 1st Row"),
             actionButton("replace", "Replace Data")),
    tabPanel("Tab 2",
             DTOutput("mt_table"))
  )
)

server <- function(input, output, session) {
  
  output$mt_table <- renderDT(mtcars)
  outputOptions(output, "mt_table", suspendWhenHidden = FALSE)
  table_proxy <- dataTableProxy("mt_table")
  
  observeEvent(input$select, {
    
    selectRows(proxy = table_proxy, selected = 1)
    
  })
  
  observeEvent(input$replace, {
    
    replaceData(proxy = table_proxy, data = rbind(mtcars, mtcars))
    
  })
  
}

shinyApp(ui, server)

It would be useful if all proxy actions would work even if the table has never been rendered. Even better would be if there was an option to render the table immediately rather than wait for the table to first become visible. This would allow for advanced modification of the table beyond just the provided proxy functions.

The only discussion I could find on this was from 2016 here. It does give a workaround which worked for that scenario. But in that case the person was wrapping the table within their own div. The workaround doesn't help when the table is in a conditional panel or a tab.

The explanation given is that due to this part, the table doesn't render until it becomes visible, i.e. if either offsetWidth or offsetHeight are 0.

.js#L183-L186

I opened an issue for this in the Github DT repo with a focus on seeing if it can be fixed within the package. But I am asking here as well to see if there is a feasible workaround that could work for now without needing to modify the package.

本文标签: rRender DT table in shiny app before it is displayedStack Overflow