Reputation: 5779
I am trying to take this basic working shiny app and modularize it. This works:
shinyApp(
ui = fluidPage(
DT::dataTableOutput("testTable"),
verbatimTextOutput("two")
),
server = function(input,output) {
output$testTable <- DT::renderDataTable({
mtcars
}, selection=list(mode="multiple",target="row"))
output$two <- renderPrint(input$testTable_rows_selected)
}
)
I want to make this a module that will work for any data.frame
# UI element of module for displaying datatable
testUI <- function(id) {
ns <- NS(id)
DT::dataTableOutput(ns("testTable"))
}
# server element of module that takes a dataframe
# creates all the server elements and returns
# the rows selected
test <- function(input,output,session,data) {
ns <- session$ns
output$testTable <- DT::renderDataTable({
data()
}, selection=list(mode="multiple",target="row"))
return(input[[ns("testTable_rows_selected")]])
}
shinyApp(
ui = fluidPage(
testUI("one"),
verbatimTextOutput("two")
),
server = function(input,output) {
out <- callModule(test,"one",reactive(mtcars))
output$two <- renderPrint(out())
}
)
This gives me errors saying I am trying to use reactivity outside of a reactive environment. If I eliminate the return statement, it runs. Is there anyway to return the rows selected from a datatable in a shiny module? Any help would be appreciated.
Upvotes: 5
Views: 1471
Reputation: 357
As the question with your own given answer is still quite relevant, I want to give an update of the code in regards of using shiny
modules:
testUI <- function(id) {
tagList(
DT::dataTableOutput(NS(id, "mytable")),
verbatimTextOutput(NS(id, "selected"))
)
}
testServer <- function(id) {
moduleServer(id, function(input, output, session) {
output$mytable <- DT::renderDataTable({
mtcars
}, selection = list(mode = "multiple", target = "row"))
output$selected <- renderPrint(
input$mytable_rows_selected # Caution: The prefix must match the id of my namespace
)
})
}
testApp <- function() {
ui <- fluidPage(
testUI("test")
)
server <- function(input, output, session) {
testServer("test")
}
shinyApp(ui, server)
}
testApp()
Upvotes: 0