Search code examples
rshinyshinydashboard

How to collapse shinydashboard::box if a mobile device is detected


Curious if anyone can offer suggestions for making shinydashboard boxes be collapsed if a mobile user is detected and expanded if a desktop user is detected. I've tried directly changing the class of the box ("box.collapsed-box"), which hasn't worked. I am thinking the way to solve this is by: 1) using an observer in the server which gives a TRUE/FALSE value if a mobile device is detected, and then 2) passing that observed value into the "collapsed" argument in the ui. That logic is laid out below. However, this isn't working as I'm getting an error that I have an invalid input.

Any help would be appreciated!

library(shiny)

ui <- fluidPage(
  shinybrowser::detect(),
  shinyWidgets::useShinydashboard(),
  br(),
  shinydashboard::box(
    title = ("This is a box"),
    width = 4,
    status = "success",
    solidHeader = T,
    collapsible = TRUE,
    collapsed = textOutput("collapse_argument"),
    "collapse when mobile, expand when desktop"
  )
)

server <- function(input, output, session) {
  observe({
    print(shinybrowser::get_device())
    output$collapse_argument <-verbatimTextOutput(
      if (shinybrowser::get_device() == "MOBILE") {
        "TRUE"
      } else {
        "FALSE"
      })
  })
}

shinyApp(ui, server)

Solution

  • We can use renderUI to achive this:

    library(shiny)
    library(shinybrowser)
    
    ui <- fluidPage(
      shinybrowser::detect(),
      shinyWidgets::useShinydashboard(),
      br(),
      uiOutput("boxOut")
    )
    
    server <- function(input, output, session) {
      output$boxOut <- renderUI({
        print(shinybrowser::get_device())
        shinydashboard::box(
          title = ("This is a box"),
          width = 4,
          status = "success",
          solidHeader = T,
          collapsible = TRUE,
          collapsed = shinybrowser::get_device() == "Mobile",
          "collapse when mobile, expand when desktop"
        )
      })
    }
    
    shinyApp(ui, server)
    

    I've been using the chrome extension Mobile simulator for testing: result

    Here is a related answer.

    Also check shinydashboardPlus::box().