This simple shiny app creates a two column table. I want to set the filterValue in the first column Name to Bob when I press the Set Filter button. At the moment, the table is displayed, but nothing happens when I press the Set Filter button.
library(shiny)
library(reactable)
# JavaScript function to set the filter
js <- "
function setReactableFilter(tableId, columnName, value) {
var reactable = Reactable.getReactable(tableId);
if (reactable) {
reactable.setFilter(columnName, value);
}
}
Shiny.addCustomMessageHandler('setFilter', function(message) {
setReactableFilter(message.tableId, message.columnName, message.value);
});
"
# Define UI for application
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
reactableOutput("table"),
actionButton("set_filter", "Set Filter")
)
# Define server logic required to render the reactable
server <- function(input, output, session) {
# Define some sample data
data <- data.frame(
Name = c("John", "Alice", "Bob", "Jane"),
Age = c(30, 25, 35, 40)
)
# Render the reactable
output$table <- renderReactable({
reactable(data, filterable = TRUE)
})
# When button is pressed, set the filter value to 'Bob' for the 'Name' column
observeEvent(input$set_filter, {
print("HELLO")
session$sendCustomMessage("setFilter", list(
tableId = "table",
columnName = "Name",
value = "Bob"
))
})
}
# Run the application
shinyApp(ui = ui, server = server)
I tried to set the filterValue of the first column to Bob by pressing the "Set Filter" button. The event is registered but nothing happens.
Don't search for the Reactable. Instead just use Reactable.setFilter()
because the first argument is the table id.
library(shiny)
library(reactable)
# JavaScript function to set the filter
js <- "
Shiny.addCustomMessageHandler('setFilter', function(message) {
Reactable.setFilter(message.tableId, message.columnName, message.value);
});
"
# Define UI for application
ui <- fluidPage(
tags$head(tags$script(js)),
reactableOutput("table"),
actionButton("set_filter", "Set Filter")
)
# Define server logic required to render the reactable
server <- function(input, output, session) {
# Define some sample data
data <- data.frame(
Name = c("John", "Alice", "Bob", "Jane"),
Age = c(30, 25, 35, 40)
)
# Render the reactable
output$table <- renderReactable({
reactable(data, filterable = TRUE)
})
# When button is pressed, set the filter value to 'Bob' for the 'Name' column
observeEvent(input$set_filter, {
session$sendCustomMessage("setFilter", list(
tableId = "table",
columnName = "Name",
value = "Bob"
))
})
}
# Run the application
shinyApp(ui = ui, server = server)