firmo23
firmo23

Reputation: 8404

Adjust box height based on object it includes in shiny dashboard

I have the shiny dashboard below with a box containing a datatable.I want the box height to be adjustable to the height of the datatable (or a plot) that is included. The box should be a little bigger every time from the table. If for example I set pageLength=10 the table will become bigger then the box should become a little bigger as well in order to fit.

library(shiny)
library(shinydashboard)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    tags$head(tags$script('
      // Define function to set height of "map" and "map_container"
      setHeight = function() {
        var window_height = $(window).height();
        var header_height = $(".main-header").height();

        var boxHeight = window_height - header_height - 30;

        $("#map_container").height(boxHeight);
        $("#map").height(boxHeight - 20);
      };

      // Set input$box_height when the connection is established
      $(document).on("shiny:connected", function(event) {
        setHeight();
      });

      // Refresh the box height on every window resize event    
      $(window).on("resize", function(){
        setHeight();
      });
    ')),
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(id = "map_container",
          dataTableOutput("map")
      )
      
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$map <- renderDataTable( {
    datatable(iris,options = list(pageLength=5))
  })
}

shinyApp(ui, server)

Upvotes: 0

Views: 792

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

According to the doc, the height of box automatically adjusts to its content. So if you want it to be a little bigger, you can do:

box(
  div(
    div(style = "height: 10px;"),
    DTOutput("yourID"),
    div(style = "height: 10px;")
  )
)

Upvotes: 1

Related Questions