Skip to content

Instantly share code, notes, and snippets.

@bborgesr
Created March 7, 2017 08:38
Show Gist options
  • Save bborgesr/c628236dabb639d57eab3e16da69920f to your computer and use it in GitHub Desktop.
Save bborgesr/c628236dabb639d57eab3e16da69920f to your computer and use it in GitHub Desktop.
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