Skip to content
Advertisement

How to block user from accessing other tabs in Shiny unless the user clicks a button?

My question is similar to Shiny how to block the user from accessing a tab?

But what I need here is: -Block other tabs unless the user clicks on a submit button -Automatically move to the other tab once that submit button is clicked. Here is an example code

library(shiny)

ui <- shinyUI(navbarPage(
  "",
  tabPanel(
    h1("Tab1"), 
    value = "nav1",
    mainPanel(
      br(),
      h2("The user must press this button to access the other tab."),
      br(),
      shiny::actionButton('button', 'press the button', onclick = "$(tab).removeClass('disabled')")
    )
  ),
  tabPanel(
    h1("Tab2"),
    value = "nav2",
    uiOutput("tab2contents")
  ),
  tags$script(
    '
    var tab = $('a[data-value="nav2"]').parent().addClass("disabled");
    $(function(){
      $(tab.parent()).on("click", "li.disabled", function(e) {
        e.preventDefault();
        return false;
      });
    });
    '
  )
))    

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

})

# Run the application
shinyApp(ui = ui, server = server)

In the above code, the 2nd tab is blocked unless the button is clicked, but how can I update this further so that once the button is clicked the user is automatically taken to the 2nd tab?

Advertisement

Answer

Since you put the tabPanel in a navbarPage you have to use updateNavbarPage. And you need to give the navbarPage an id.

library(shiny)

ui <- shinyUI(navbarPage(
  "", id = "mainpage",
  tabPanel(
    h1("Tab1"), 
    value = "nav1",
    mainPanel(
      br(),
      h2("The user must press this button to access the other tab."),
      br(),
      shiny::actionButton('button', 'press the button', onclick = "$(tab).removeClass('disabled')")
    )
  ),
  tabPanel(
    h1("Tab2"),
    value = "nav2",
    uiOutput("tab2contents")
  ),
  tags$script(
    '
    var tab = $('a[data-value="nav2"]').parent().addClass("disabled");
    $(function(){
      $(tab.parent()).on("click", "li.disabled", function(e) {
        e.preventDefault();
        return false;
      });
    });
    '
  )
))    

server <- shinyServer(function(input, output) {
  observeEvent(input$button,
               {
                 updateNavbarPage(inputId = "mainpage", selected = "nav2")
               }, ignoreInit = TRUE)
})

# Run the application
shinyApp(ui = ui, server = server)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement