Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to make a DataTable actually become hidden in a Shiny app
# -------------------------------------------------------------------
# ------------------ HIDIND A DATATABLE IN SHINY --------------------
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# --- EXAMPLE 1: this sets the datatable's underlying dataframe to --
# --- NULL, inside a reactive (recalculated whenever a checkbox is --
# --- clicked). While this does result in the datatable disappearing
# --- from view, the height does not show ---------------------------
# -------------------------------------------------------------------
# -------------------- does not work as intended --------------------
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(checkboxInput("chk", label = "NULL: ", value = T)),
dashboardBody(
box(width = 8, DT::dataTableOutput("test"))
)
)
server <- function(input, output, session) {
df <- reactive({
if (input$chk) NULL else data.frame(A = 1:20, B = 2*1:20)
})
output$test <- DT::renderDataTable({
datatable(df())
})
}
shinyApp(ui = ui, server = server)
# -------------------------------------------------------------------
# --- EXAMPLE 2: this leaves the datatable's underlying dataframe ---
# --- untouched, and instead uses shinyjs to hide the dataTableOutput
# --- when the checkbox is clicked. Now, the height readjusts as ----
# --- expected ------------------------------------------------------
# ------------------------ works as intended ------------------------
library(shiny)
library(shinydashboard)
library(DT)
library(shinyjs) # requires shinyjs !
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(checkboxInput("chk", label = "NULL: ", value = T)),
dashboardBody(useShinyjs(),
box(width = 8, DT::dataTableOutput("test"))
)
)
server <- function(input, output, session) {
observeEvent(input$chk, {
if (input$chk) hide("test") else show("test")
})
output$test <- DT::renderDataTable({
datatable(data.frame(A = 1:20, B = 2*1:20))
})
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment