I have an R Shiny App with a Data Table. One column contains action buttons with a unique ID. I'd like to handle clicks on those buttons, but unfortunately, my event handling code (a simple print statement) is never executed. See this self-contained example (app.R
):
library(shiny)
library(DT)
ui <- shinyUI(
fluidPage(
title = "DataTable with Buttons",
fluidRow(
column(
width = 8,
dataTableOutput("employees")
)
)
)
)
server <- shinyServer(function(input, output) {
df <- data.frame(
name = c('Dilbert', 'Alice', 'Wally', 'Ashok', 'Dogbert'),
motivation = c(62, 73, 3, 99, 52),
stringsAsFactors = FALSE
)
fireButtons <- list()
fireButtonIds <- list()
for (r in rownames(df)) {
id <- paste("fire_", r, sep = "")
fireButtonIds[[r]] <- id
button <- actionButton(id, label = "Fire")
fireButtons[[r]] <- as.character(button)
}
df$actions <- fireButtons
dt <- datatable(df, colnames = c("#", "Name", "Motivation", "Actions"))
output$employees <- renderDataTable(dt)
for (id in fireButtonIds) {
# binding doesn't work
# - is the path wrong?
# - is it because the button is really a string, not an object?
observeEvent(input$employees$x$data$actions[[id]], {
print(paste("click on", i))
})
}
})
shinyApp(ui = ui, server = server)
I see two possible problems:
- The path I'm using (
input$employees$x$data$actions[[id]]
) is just wrong - The path I'm using is correct, but it doesn't point to something that could actually be handled, i.e. it's just a HTML string and not a button object.
Or maybe there's a much better approch to put buttons inside a data table...?