Search code examples
javascriptrshinyshinydashboard

R shiny dashboard, show conditionalPanel only when a specific tabPanel within a specific sidebar menuItem is selected


Below I have provided the skeleton of a Shiny Dashboard that I am trying to create. I've fought with this for quite a while and cannot figure out how to make it work.

App Current Behavior: Right now the "Select Date Range" date input is visible when the Menu Item 1 sidebar item is selected.

Desired Behavior: I would like the "Select Date Range" input to only be visible when "Menu Item 1" and "Tab 1" are selected simultaneously.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(lubridate)

generate_dates <- function(start_date, end_date) {
  all_dates <- seq(start_date, end_date, by = "days")
  all_mondays <- all_dates[weekdays(all_dates) == "Monday"]
  return(all_mondays)
}

start_date <- floor_date(as.Date("2023-07-01"), unit = "week", week_start = 1)
end_date <- floor_date(as.Date("2023-12-06"), unit = "week", week_start = 1)
dates <- generate_dates(start_date, end_date)

df <- data.frame(
  Week = dates,
  Value_1 = sample(c("A", "B", "C", "D"), length(dates), replace = TRUE),
  Value_2 = sample(c("X", "Y", "Z", "W"), length(dates), replace = TRUE)
)


sidebar <- dashboardSidebar(
  sidebarMenu(
    id= "sidebarID",
    conditionalPanel(
      condition="input.sidebarID =='menu1'",
      dateRangeInput("date_range","Select Date Range",
                     start=max(df$Week),
                     end=max(df$Week),
                     min=max(df$Week),
                     max=max(df$Week),
                     format="yyyy-mm-dd"
                     )
    ),
    menuItem("Menu Item 1",tabName="menu1"),
    menuItem("Menu Item 2",tabName="menu2")
  )
)

body<- dashboardBody(
  tabItems(
    tabItem(tabName="menu1",
            tabsetPanel(
              tabPanel("Tab 1"),
              tabPanel("Tab 2")
            )),
    tabItem(tabName="menu2")
  )
)

ui<-dashboardPage(
  dashboardHeader(title="Navigation"),
  sidebar,
  body
)

server<-function(input,output,session){
  
  
  
}

shinyApp(ui,server)

I have tried many different attempts involving different conditions in the conditionalPanel but nothing has worked.


Solution

  • If your inner tabs an ID

    body<- dashboardBody(
      tabItems(
        tabItem(tabName="menu1",
                tabsetPanel(id="innerTab",
                  tabPanel("Tab 1"),
                  tabPanel("Tab 2")
                )),
        tabItem(tabName="menu2")
      )
    )
    

    and then use that in the condition for rendering

    conditionalPanel(
          condition="input.sidebarID =='menu1' & input.innerTab=='Tab 1'",
          ...
    )