Search code examples
rshinyshinydashboard

shinydashboard toggle box - hide by default


This is a follow up to a previous thread. The answers give an option which shows the box by default, but how can I change it to be hidden by default? Below code a mix of both answers.

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      useShinyjs()
    ),
    mainPanel(
      box(id = "myBox", title = "Tree Output", width = '800px',
          selectInput(inputId = "myInput", label = "my input", choices = c(letters))
      ),
      actionButton(inputId = "button", label = "show / hide")
    )
  )
)

server <- function(input, output){

  ## observe the button being pressed
  observeEvent(input$button, {
    shinyjs::toggle("myBox")
  })
}

shinyApp(ui, server)

Solution

  • You can wrap it around another div and use hidden function from shinyjs

    library(shiny)
    library(shinydashboard)
    library(shinyjs)
    
    ui <- fluidPage(
        sidebarLayout(
            sidebarPanel(
                useShinyjs()
            ),
            mainPanel(
                hidden(
                    div(id = "mybox_wrapper",
                        box(id = "myBox", title = "Tree Output", width = '800px',
                            selectInput(inputId = "myInput", label = "my input", choices = c(letters))
                        )
                    )),
                actionButton(inputId = "button", label = "show / hide")
            )
        )
    )
    
    server <- function(input, output){
    
        ## observe the button being pressed
        observeEvent(input$button, {
            shinyjs::toggle("mybox_wrapper")
        })
    }
    
    shinyApp(ui, server)
    

    enter image description here