Created
April 22, 2023 09:32
-
-
Save nbenn/14f156ef7210f34172b0f96b75603a69 to your computer and use it in GitHub Desktop.
Simple DT/reactive example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##### 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