I want to display inputs (checkboxes, select input) in the sidebar of my shiny dashboard, but only when a certain tab is clicked.
Minimum reporducible example below. How can I get the checkboxes and select input to only show up when on Page 2?
#ui.R
library(shiny)
library(shinydashboard)
# Define UI for application that draws a histogram
shinyUI(dashboardPage(
dashboardHeader(title = "Test Application",
titleWidth = "400px"
),
dashboardSidebar(
id = "navbar",
menuItem("Page 1", tabName = "page1"),
menuItem("Page 2", tabName = "page2"),
# THESE SHOW UP ALL THE TIME - HOW TO GET JUST ON PAGE 2?
checkboxGroupInput("outcome", "Select Outcome Variable(s):", choices = c("Box 1", "Box 2", "Box 3")),
selectInput("selectinput", label = "Select:", choices = c("Choice 1", "Choice 2", "Choice 2"))
),
dashboardBody(
tabItems(
tabItem(
tabName = "page1",
h1("This is page 1")
),
tabItem(
tabName = "page2",
h1("This is page 2")
)
)
)
))
I assume something is needed in here to make the inputs dynamic?
# server.R
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
})
ANSWER: use a conditional panel that queries the selected tab.
Credit: Mine at Rstudio
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)