Schalk Burger
Schalk Burger

Reputation: 78

Using a reactive value in an IF-statement in the UI in R Shiny

I am trying to create a conditional UI in Shiny that depends on the input of a user. I specifically want to do the if in the UI part and NOT in the server part.

Here is an example of what I aim to accomplish.

# app.R

library(shiny)

ui <- shiny::fluidPage(
  shiny::headerPanel(title = "Basic App"),
  shiny::sidebarPanel(
    shiny::sliderInput(inputId = "a",
                       label = "Select an input to display",
                       min = 0, max = 100, value = 50
    )
  ),
  if(output$out < 50){
    shinyjs::hide(shiny::mainPanel(h1(textOutput("text"))))
  }else{
    shiny::mainPanel(h1(textOutput("text")))
  }

)

server <- function(input, output) {
  output$text <- shiny::renderText({
    print(input$a)
  })

  var <- shiny::reactive(input$a)

  output$out <- renderText({ var() })
}

shiny::shinyApp(ui = ui, server = server)

Is there a way that I can use the reactive value in the UI part of the function?

Upvotes: 0

Views: 1699

Answers (1)

Bertil Baron
Bertil Baron

Reputation: 5003

I think conditionalPanel could be a good solution for what you want to do

library(shiny)

ui <- shiny::fluidPage(
  shiny::headerPanel(title = "Basic App"),
  shiny::sidebarPanel(
    shiny::sliderInput(inputId = "a",
                       label = "Select an input to display",
                       min = 0, max = 100, value = 50
    )
  ),
  shiny::mainPanel(
    conditionalPanel(
      condition = "input.a > 50",
      h1(textOutput("text")))
    )

)

server <- function(input, output) {
  output$text <- shiny::renderText({
    print(input$a)
  })
}

shiny::shinyApp(ui = ui, server = server)

Hope this helps!!

Upvotes: 2

Related Questions