1

I have this simple app and I would like to be able to "catch" the active tab. For example, if I'm on "tab1", my selectInput at the top would be c("a","b","c") but it would change if I am on the other tab I want to create a variable active_tab that would be dynamic but I have no idea how to do it.

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)


shinyApp(
  ui = dashboardPage(
    title="Shiny Dashboard",
    header = shinydashboardPlus::dashboardHeader(
      title = "Example",
      leftUi = tagList(
        uiOutput("reactive_ui")
      )),
    
    sidebar = dashboardSidebar(
      sidebarMenu(
        menuItem("tab1",tabName = "tab1"),
        menuItem("tab2",tabName = "tab2")
      )
    ),
    body = dashboardBody(
      tabItems(
        tabItem("tab1"),
        tabItem("tab2")
      )
    )
  ),
  
  server = function(input, output) {
    output$reactive_ui =renderUI({
      if (active_tab == "tab1") choice = c("a","b","c","d") 
      if (active_tab == "tab2") choice = c("e","f","g")
      
      selectInput("select", NULL,choices = choice )
    })
  }
)


 

1 Answer 1

3

sidebarMenu contains an id parameter that can be used to retrieve the name of the active tab on the server side.

If it is just the selectInput you want to update on the tab change, then have a look at updateSelectInput so that you can update the choices without having to re-render the input every time the tab changes. It also means the input is defined once the application opens.

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)

shinyApp(
  ui = dashboardPage(
    title = "Shiny Dashboard",
    header = shinydashboardPlus::dashboardHeader(
      title = "Example",
      leftUi = tagList(
        selectInput("select", NULL, choices = c("a", "b", "c", "d"))
      )
    ),
    
    sidebar = dashboardSidebar(
      sidebarMenu(
        id = "tab",
        menuItem("tab1", tabName = "tab1"),
        menuItem("tab2", tabName = "tab2")
      )
    ),
    body = dashboardBody(
      tabItems(
        tabItem("tab1"),
        tabItem("tab2")
      )
    )
  ),
  
  server = function(input, output, session) {
    observeEvent(input$tab, {
      if (input$tab == "tab1") {
        choices <- c("a", "b", "c", "d")
      } else if (input$tab == "tab2") {
        choices <- c("e", "f", "g")
      }
      updateSelectInput(session, "select", choices = choices)
    })
  }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.