Home > Enterprise >  How to conditionally render a well panel in R Shiny?
How to conditionally render a well panel in R Shiny?

Time:10-15

Is it possible to conditionally render a wellPanel() (or equivalent) in R?

In the below code, clicking "Show!" correctly renders two objects jointly. I'd like them surrounded by a wellPanel() (or eqivalent shading) when they appear and have the wellPanel() disappear when clicking "Hide!". When first invoking the App, the default state is the two objects are hidden and the wellPanel() should also remain hidden.

Is there some CSS wizardry available for doing this sort of thing? Or other trick?

For many reasons I need to keep the general structure of this using shinyjs, the toggleView() function, etc.

Code:

library(shiny)
library(shinyjs)

toggleView <- function(input, output_name){
  observeEvent(input$show, {show(output_name)})
  observeEvent(input$hide, {hide(output_name)})
}

ui <- fluidPage(
  useShinyjs(), 
  br(),
  actionButton("hide","Hide!"),
  actionButton("show","Show!"),
  br(),
  fluidRow(
    column(2,h5(hidden(textOutput("text")))),   
    column(6,hidden(tableOutput("table")))
  )
)

server <- function(input, output, session) {
  output$table <- renderTable(iris[1:5,1:3])
  output$text <- renderText("Test show/hide in JS")
  toggleView(input, "table")
  toggleView(input, "text")
}

shinyApp(ui, server)

CodePudding user response:

You can specify an id for the fluid row (or any parent element):

## UI part
## ... 
    fluidRow(id = "my_well",
## ... 

and use this id to add/remove CSS classes with shinyjs:

## server part
## ...
  observeEvent(input$show, addClass("my_well", "well"), ignoreInit = TRUE)
  observeEvent(input$hide, removeClass("my_well", "well"), ignoreInit = TRUE)
## ...

CodePudding user response:

You can give a HTML id to the wellpanels. The shinyjs functions show and hide are not restricted to output elements.

library(shiny)
library(shinyjs)

toggleView <- function(input, id){
  observeEvent(input$show, {show(id)})
  observeEvent(input$hide, {hide(id)})
}

ui <- fluidPage(
  useShinyjs(), 
  br(),
  actionButton("hide", "Hide!"),
  actionButton("show", "Show!"),
  br(),
  fluidRow(
    column(
      2,
      hidden(
        wellPanel(
          id = "panel_text",
          h5(textOutput("text"))   
        )
      )
    ),   
    column(
      6,
      hidden(
        wellPanel(
          id = "panel_table",
          tableOutput("table")
        )
      )
    )
  )
)

server <- function(input, output, session) {
  output$table <- renderTable(iris[1:5,1:3])
  output$text <- renderText("Test show/hide in JS")
  toggleView(input, "panel_table")
  toggleView(input, "panel_text")
}

shinyApp(ui, server)
  • Related