Skip to content

Instantly share code, notes, and snippets.

@nbenn
Created April 22, 2023 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbenn/14f156ef7210f34172b0f96b75603a69 to your computer and use it in GitHub Desktop.
Save nbenn/14f156ef7210f34172b0f96b75603a69 to your computer and use it in GitHub Desktop.
Simple DT/reactive example
##### Use of reactive() #####
library(shiny)
library(dplyr)
library(DT)
dt <- data.frame(
id = c(1, 1, 2),
text = c("text1", "text2", "text1")
)
ui <- fluidPage(
selectInput(inputId = "id", label = "Choose id", choices = unique(dt$id)),
dataTableOutput("table"),
actionButton(inputId = "add", label = "Add row"),
textInput(inputId = "text", label = "Updated text", value = "")
)
server <- function(input, output, session) {
df <- reactive({
dt %>% filter(id == input$id)
})
output$table <- renderDataTable({
datatable(
data = df(),
selection = "single",
options = list(dom = 't')
)
})
observeEvent(input$table_cell_clicked, {
tab <- df() %>%
slice(input$table_rows_selected)
updateTextInput(session = session, inputId = "text", value = tab$text)
})
observeEvent(input$add, {
old <- df()
new <- data.frame(
id = unique(old$id),
text = paste0("text", nrow(old) + 1L)
)
output$table <- renderDataTable({
datatable(
data = rbind(new, old),
selection = "single",
options = list(dom = 't')
)
})
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment