Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Switch Between NavBar Tabs with a Button R Shiny

Tags:

r

shiny

I need the user to click a button and be taken to a different tabPanel of a navbarPage. Here is a simple app where this could be implemented. How can I achieve this?

ui <- shinyUI(
 navbarPage('Test App',
  tabPanel('Page 1',
   p('This is the first tab'), br(),
   actionButton('jumpToP2', 'Jump to Second Tab')
  ),

  tabPanel('Page 2',
   p('This is the second tab'),
   actionButton('jumpToP1', 'Jump to First Tab')
  )
 )
)

server <- shinyServer(function(input, output){
  observeEvent(input$jumpToP2,{
    ## Switch active tab to 'Page 2'
  })

  observeEvent(input$jumpToP1,{
    ## Switch active tab to 'Page 1'
  })
})

shinyApp(ui, server)
like image 959
tsouchlarakis Avatar asked Apr 21 '17 22:04

tsouchlarakis


1 Answers

You can use updateTabsetPanel to switch between different tabPanels. See the documentation and example codes at https://shiny.rstudio.com/reference/shiny/latest/updateTabsetPanel.html. The code below should fulfill your requirements.

ui <- navbarPage('Test App',id = "inTabset",
                 tabPanel(title = "Panel 1", value = "panel1", 
                          actionButton('jumpToP2', 'Jump to Second Tab')),
                 tabPanel(title = "Panel 2", value = "panel2", 
                          actionButton('jumpToP1', 'Jump to First Tab'))
        )

server <- function(input, output, session) {
    observeEvent(input$jumpToP2, {
        updateTabsetPanel(session, "inTabset",
                          selected = "panel2")
    })

    observeEvent(input$jumpToP1, {
        updateTabsetPanel(session, "inTabset",
                          selected = "panel1")
    })

}

shinyApp(ui, server)
like image 165
discipulus Avatar answered Nov 05 '22 07:11

discipulus