How to Switch Between NavBar Tabs with a Button R Shiny

非 Y 不嫁゛ 提交于 2020-01-12 06:59:09

问题


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)

回答1:


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)



回答2:


I'm not so sure that this really the best way for you to design your U... Do you know that tabPanel() will act pretty much the same way as an actionButton() will in this case?

ui <- navbarPage('Test App',id = "inTabset",
             tabPanel(title = "Panel 1", uiOutput("panel1")),                       
             tabPanel(title = "Panel 2", uiOutput("panel2")) 
                      )
server <- function(input, output, session) {
    output$panel1 <- renderUI({
    #your UI data
    })
    output$panel2 <- renderUI({
    #your UI data
    })
}
shinyApp(ui, server)


来源:https://stackoverflow.com/questions/43552906/how-to-switch-between-navbar-tabs-with-a-button-r-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!