1

I am trying to use a button to change pages in a shiny app. I have found examples like this one that seem pretty straight forward but for some reason I am not able to make it work. Below is a reproducible example I created in an app.R file. This creates a two page app with a button on the first page but clicking the button does not move you to the second page. Any tips would be greatly appreciated.

pageButtonUi <- function(id) {
  actionButton(NS(id, "page_change"),
               label="Change the Page")
}


pageButtonServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
    observeEvent(input$page_change, {
      updateNavbarPage(session=session,
                       inputId="pages",
                       selected="second_page")
    })
  })
}


ui <- navbarPage(
  title="test",
  id="pages",
  tabPanel(title="first page",
           sidebarLayout(
             sidebarPanel(
               pageButtonUi("page")
             ),
             mainPanel(
             )
           )
  ),
  tabPanel(title="second_page", "second_page")
)


server <- function(input, output, session) {
  pageButtonServer("page")
}


shinyApp(ui, server)
Hunter Clark
  • 181
  • 13

1 Answers1

2

You are using shiny modules. The tabPanel is defined in the top-level UI, but your are trying to use a lower-level (module) server to update the top-level UI. This will not work. So you need to use top-level server to update top-level UI. In other words, you need to pass the parent session object to your module.

This is how to fix:

library(shiny)


pageButtonUi <- function(id) {
    actionButton(NS(id, "page_change"),
                 label="Change the Page")
}


pageButtonServer <- function(id, parentSession) {
    moduleServer(id, function(input, output, session) {
        
        observeEvent(input$page_change, {
            updateNavbarPage(session=parentSession,
                             inputId="pages",
                             selected="second_page")
        })
    })
}


ui <- navbarPage(
    title="test",
    id="pages",
    tabPanel(title="first page",
             sidebarLayout(
                 sidebarPanel(
                     pageButtonUi("page")
                 ),
                 mainPanel(
                 )
             )
    ),
    tabPanel(title="second_page", "second_page")
)


server <- function(input, output, session) {
    pageButtonServer("page", parentSession = session)
}


shinyApp(ui, server)

This is not easy to understand even for advanced users. Try to read Rstudio articles see how they define session will be helpful.

lz100
  • 6,990
  • 6
  • 29