What is the best way to make an output component (like @render.text) know the screen width. I want to change how a table and graph are generated based on the bootstrap screen size.
1 Like
The best way to make an output component (like @render.text
) aware of screen width in Shiny (R framework) is to use JavaScript to detect screen size and pass it to R via shinyjs
or shiny::updateTextInput()
.
Example:
- Use JavaScript in UI to detect screen width
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
tags$script(HTML("
$(document).on('shiny:connected', function() {
Shiny.setInputValue('screen_width', window.innerWidth);
});
$(window).resize(function() {
Shiny.setInputValue('screen_width', window.innerWidth);
});
")),
verbatimTextOutput("screen_info"),
uiOutput("dynamic_output")
)
server <- function(input, output, session) {
output$screen_info <- renderText({
paste("Screen width:", input$screen_width)
})
output$dynamic_output <- renderUI({
if (is.null(input$screen_width)) return(NULL)
if (input$screen_width < 768) {
tableOutput("small_table")
} else {
plotOutput("large_graph")
}
})
output$small_table <- renderTable({ head(mtcars, 5) })
output$large_graph <- renderPlot({ plot(mtcars$mpg, mtcars$hp) })
}
shinyApp(ui, server)
This approach dynamically updates the UI based on screen size, ensuring responsive behavior.
I'd suggest to take a look at the css unit vw (viewport width):