Search code examples
rshinyshinydashboard

Make the column width dynamic in a shiny app


In the shiny app below Im trying to set the column width based on the shiny widget but I get column width must be between 1 and 12

## app.R ##
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "VMT-Mobility"),
  dashboardSidebar(
  
    
  ),
  dashboardBody(
    
    fluidRow(
      
      column(3,
             pickerInput(
               inputId = "cat",
               label = "Select categories",
               choices = c("1st","2nd"),
               selected="1st",
               multiple = F,
               
             )
      )
    ),
    fluidRow(
  
      column(uiOutput("n1"),box()),
      column(uiOutput("n2"),box())
      
      
      
    )
    
  )
)

server <- function(input, output) {
  output$n1<-renderUI({
    if(input$cat=="1st"){
      9
    }
    else{
      3
    }
  })
  output$n2<-renderUI({
    if(input$cat=="1st"){
      3
    }
    else{
      9
    }
  })
  
}

shinyApp(ui, server)

Solution

  • At the moment, you're passing a UI element into column when it expects a numeric value. You could try creating reactive values in the server to calculate the widths, and construct the columns in the server using those reactive values e.g.

    library(shiny)
    library(shinydashboard)
    library(shinyWidgets)
    library(DT)
    
    ui <- dashboardPage(
      dashboardHeader(title = "VMT-Mobility"),
      dashboardSidebar(
        
        
      ),
      dashboardBody(
        
        fluidRow(
          
          column(3,
                 pickerInput(
                   inputId = "cat",
                   label = "Select categories",
                   choices = c("1st","2nd"),
                   selected="1st",
                   multiple = F,
                   
                 )
          )
        ),
        uiOutput("cols")
        
      )
    )
    
    server <- function(input, output) {
      
      n1 <- eventReactive(input$cat, {
        if(input$cat=="1st"){
          9
        }
        else{
          3
        }
      })
      
      n2<- eventReactive(input$cat, {
        if(input$cat=="1st"){
          3
        }
        else{
          9
        }
      })
      
      output$cols <- renderUI({
        fluidRow(
          column(width = n1(), box(width = 12)),
          column(width = n2(), box(width = 12))
        )
      })
      
    }
    
    shinyApp(ui, server)