简体   繁体   中英

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?

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM