Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional panel message flashes and then disappears when initializing app

Tags:

shiny

When I run the below app, the red message in the conditional panel statement flashes and disappears. Can someone explain why, and how to remove it?

library(shiny)

ui <- fluidPage(
  numericInput("num", "Choose a number",1.1,1,10),
  conditionalPanel(
    condition = "output.square",
    div("That's a perfect square!",style="color:red; height:400px")
  )
)

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)
like image 616
roccomay Avatar asked Nov 15 '25 11:11

roccomay


1 Answers

I ran into the same problem some time ago and got it answered on GitHub.

When calling a conditionalPanel a div tag is created. This div tag by default is visible - once the condition is checked it's hidden.

To hide it right from the start we can add a style attribute setting display: none; for conditionalPanel (Please see the example below).

I'd prefer conditionalPanel over renderUI as we avoid the time consuming detour to the server.

library(shiny)

ui <- fluidPage(
  numericInput("num", "Choose a number", 1.1, 1, 10),
  conditionalPanel(
    condition = "output.square",
    div("That's a perfect square!", style = "color:red; height:400px;"),
    style = "display: none;"
  )
)

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)

Edit: Another option to avoid the flashing is using a "proper" conditional statement like output.square == true.

The reason for this is given here:

Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

Accordingly as soon as output.square is not null the condition evaluates to true.

library(shiny)

ui <- fluidPage(
  numericInput("num", "Choose a number", 1.1, 1, 10),
  conditionalPanel(
    condition = "output.square == true",
    div("That's a perfect square!", style = "color:red; height:400px;"),
    style = "display: none;"
  )
)

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)
like image 166
ismirsehregal Avatar answered Nov 18 '25 18:11

ismirsehregal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!