3
votes

writing with a shiny question. I have a navbarPage, id = "navbar", and in the navbarMenu user can select one among several tabPanels. Each tabPanel is assigned a value (value = 1, value = 2, etc). So input$navbar is reactive value with the value of the selected tabPanel.

I have a reactive expression defined which reacts to the changing of the tabPanel (reacts based on input$navbar). What I actually want is for this to react to navigating to a particular tabPanel, but not navigating away from that tabPanel. So, when input$navbar changes from 1 to 2 I want a reaction, but when changing from 2 to 1 no reaction. How can I achieve this?

Here is relevant snippet of my code, I don't think I need a full reproducible example for this but let me know if I'm wrong.

#ui snippet
navbarPage(id = "navbar",
        navbarMenu(title = "Title",
                    tabPanel(title = "tp1", value = 1),
                    tabPanel(title = "tp2", value = 2),
                    #more tabPanels and ui stuff...

#server snippet
rctvfx <- reactive({
              #want this to react only when input$navbar changes from ==1 to ==2
              input$navbar 
              isolate({ 
                  #do stuff 
              })
          })
1

1 Answers

5
votes

You can use an if statement. This makes sure the code only runs if the user navigated to the corresponding tab.

library(shiny)

shinyApp(
  ui = navbarPage(
    "App Title",
    id = "navbar",
    tabPanel("Plot"),
    navbarMenu(
      "More",
      tabPanel("Summary"),
      "----",
      "Section header",
      tabPanel("Table")
    )
  ),
  server = function(input, output){
    observe({
      if (req(input$navbar) == "Table")
        message("Table has been selected")
      if (req(input$navbar) == "Plot")
        message("Plot has been selected")
    })
  }
)

I would recomment do use observe rather than reactive to make sure everything runs even if all observers for the reactive are idle.