Search code examples
rshinyreactivedt

How to get the cell clicked from a dataTable in a dynamic UI?


Consider this example with two dataTables. One of them is generated dynamically but I do not know how to get cell-clicked events from it.

library(shiny)
library(DT)

ui <- fluidPage(
  textOutput("out"),
  uiOutput("dynamic"),
  DTOutput("normal")
)

server <- function(input, output, session) {
  output$dynamic <- renderUI(
    renderDT(mtcars,
             rownames = FALSE,
             selection = list(mode = "single", target = "cell"),
             options   = list(dom  = "t"     , pageLength = 5))
  )

  output$normal <- renderDT(iris,
                            rownames = FALSE,
                            selection = list(mode = "single", target = "cell"),
                            options   = list(dom  = "t"     , pageLength = 5))


  output$out <- renderText({
    paste("Normal",  paste(input$normal_cells_selected, collapse = ""), "\n",
          "Dynamic", paste(input$dynamic_cells_selected, collapse = "")     )
  })
}

shinyApp(ui, server)


Solution

  • I'm not convinced this is the best way to do this but I have managed to get it to work with a few amendments. Let me know how you get on......

    library(shiny)
    library(DT)
    
    ui <- fluidPage(
      textOutput("out"),
      uiOutput("dynamic"),
      DTOutput("normal")
    )
    
    server <- function(input, output, session) {
      output$dynamic <- renderUI({
        output$aa <- renderDT(mtcars,
                              rownames = FALSE,
                              selection = list(mode = "single", target = "cell"),
                              options   = list(dom  = "t"     , pageLength = 5))
        DTOutput("aa")
      })
      
      output$normal <- renderDT(iris,
                                rownames = FALSE,
                                selection = list(mode = "single", target = "cell"),
                                options   = list(dom  = "t"     , pageLength = 5))
      
      
      output$out <- renderText({
        paste("Normal",  paste(input$normal_cells_selected, collapse = ""), "\n",
              "Dynamic", paste(input$aa_cells_selected, collapse = ""))
      })
    }
    
    shinyApp(ui, server)