Why can server variables be used in the condition for a conditionalPanel but nowhere else in UI?

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)

With that code (taken straight from https://github.com/daattali/advanced-shiny/blob/master/server-to-ui-variable/app.R), the conditional panel can depend a variable in the server. But is it not possible to use that variable anywhere else?

For example, I would like to replace "That's a perfect square!" with paste("It is ", output.square, " that the number is a perfect square!") but when I try to use output.square there I get an error that the variable is not defined. But clearly is it defined, since the condition is using it...

Thats javascript, not R language.

That said, this is likely an approach that will be more generally useful to you.

library(shiny)

ui <- fluidPage(
  selectInput("num", "Choose a number", 1:10),
  uiOutput("square_report")
)

server <- function(input, output, session) {
  
  square <- reactive({
    sqrt(as.numeric(input$num)) %% 1 == 0
  })
  
  output$square_report <- renderUI({
    p(paste0("it is ",req(square()), "That's a perfect square!"))
  })

}
shinyApp(ui = ui, server = server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.