Gaurav Bansal Gaurav Bansal - 4 months ago 25
R Question

Changing value of element based on selected tab in shinydashboard

I'm trying to create an app using

shinydashboard
in which there is a reactive element that changes value based on which tab is selected. Below is the code I've got in an app.R file. There is an if/else statement currently commented out that I want to be able to use. The if/else statement would change the value of
answer
based on which tab is selected.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
dashboardHeader(title='Title'),
dashboardSidebar(
sidebarMenu(
menuItem('Models', tabName='Models',
menuSubItem('Model1', tabName='Model1'),
menuSubItem('Model2', tabName='Model2')
),
tags$head(tags$script(HTML('$(document).ready(function() {$(".treeview-menu").css("display", "block");})')))
)
),
dashboardBody(
tabItems(
tabItem(tabName='Model1',
h1("Model 1"),
verbatimTextOutput('out1')
),
tabItem(tabName='Model2',
h1("Model 2"),
verbatimTextOutput('out2')
)
)
)
)

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

answer <- reactive({
#if(selected tabName=='Model1'){
answer <- 1
#} else if(selected tabName=='Model2'){
answer <- 2
#}
return(answer)
})

output$out1 <- renderPrint(answer())
output$out2 <- renderPrint(answer())
}

shinyApp(ui, server)

Answer

The solution to this is actually very easy and quite elegant. You have to give sidebarMenu an ID, say, tab and input$tab is going to report which tab is selected.

So, your if-else statement is going to look like this:

if (input$tab == 'Model1'){
      answer <- 1
    } else if (input$tab == 'Model2'){
      answer <- 2
    }

Full example:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title='Title'),
  dashboardSidebar(
    sidebarMenu(id = "tab", # added ID 
      menuItem('Models', tabName='Models',
               menuSubItem('Model1', tabName='Model1'),
               menuSubItem('Model2', tabName='Model2')
      ),
      tags$head(tags$script(HTML('$(document).ready(function() {$(".treeview-menu").css("display", "block");})')))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName='Model1',
              h1("Model 1"),
              verbatimTextOutput('out1')
      ),
      tabItem(tabName='Model2',
              h1("Model 2"),
              verbatimTextOutput('out2')
      )
    )
  )
)

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

  observe({
    print(input$tab)
  })

  answer <- reactive({
    if (input$tab == 'Model1'){
      answer <- 1
    } else if (input$tab == 'Model2'){
      answer <- 2
    }
    return(answer)
  })

  output$out1 <- renderPrint(answer())
  output$out2 <- renderPrint(answer())
}

shinyApp(ui, server)