How to pass a variable from server.R to ui.R in shiny without global?

tonybrown picture tonybrown · Jan 26, 2017 · Viewed 7k times · Source

I've tried different ways to store a variable in server.R and use the same variable in ui.R without much success.(except declaring it global) Is there a way to pass a variable to ui.R from server.R? It could be a hacky way as long as it works.

Answer

DeanAttali picture DeanAttali · Jan 27, 2017

This might be useful to you (taken directly from my Shiny tips 'n tricks list):

Use a variable from the server in a UI conditionalPanel()

When using a conditional panel in the UI, the condition is usually an expression that uses an input value. But what happens when you want to use a conditional panel with a more complex condition that is not necessarily directly related to an input field? This example shows how to define an output variable in the server code that you can use in the UI. An alternative approach is to use the show() and hide() functions from the shinyjs package.

library(shiny)

ui <- fluidPage(
  selectInput("num", "Choose a number", 1:10),
  conditionalPanel(
    condition = "output.square",
    "That's a perfect square!"
  )
)

server <- function(input, output, session) {
  output$square <- reactive({
    sqrt(as.numeric(input$num)) %% 1 == 0
  })
  outputOptions(output, 'square', suspendWhenHidden = FALSE)
}

shinyApp(ui = ui, server = server)