Include input on Shiny/shinydashboard sidebar only under certain tabs. - COVID19 Research

Names: Adam
From: University of Washington


I am creating a Shiny dashboard so others can explore daily diary data I am collecting on mental health during the COVID-19 pandemic/social distancing.

I need to include sidebar inputs (selectInput, sliderInput, etc.) in the side bar, but these need to change depending on which tab is open. I have spent hours trying to figure this out and can't!

I've posted a minimal reproducible example here:


I do not think it matters, but the inputs control plot parameters that are on each tab!

1 Like

You can do this with the use of conditionalPanel() and capturing the id of the sidebarMenu.

library(shiny)
library(shinydashboard)

# ui ---------------------------------------------------------------------------

ui <- dashboardPage(
  
  # title ----
  dashboardHeader(title = "Test Application"),
  
  # sidebar ----
  dashboardSidebar(
    sidebarMenu(id = "sidebarid",
                menuItem("Page 1", tabName = "page1"),
                menuItem("Page 2", tabName = "page2"),
                conditionalPanel(
                  'input.sidebarid == "page2"',
                  sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
                  selectInput("title", "Select plot title:", choices = c("Hist of x", "Histogram of x"))
                )
    )
  ),
  
  # body ----
  dashboardBody(
    tabItems(
      # page 1 ----
      tabItem(tabName = "page1", "Page 1 content. This page doesn't have any sidebar menu items."),
      # page 2 ----
      tabItem(tabName = "page2", 
              "Page 2 content. This page has sidebar meny items that are used in the plot below.",
              br(), br(),
              plotOutput("distPlot"))
    )
  )
)

# server -----------------------------------------------------------------------

server <- function(input, output, session) {
  
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = "darkgray", border = "white", main = input$title)
  })
  
}

# shiny app --------------------------------------------------------------------

shinyApp(ui, server)
4 Likes

Wow - so straightforward. Thank you so much!

-Adam

1 Like

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