简体   繁体   中英

R shiny: Switching tabs programmatically using shinymaterial

I'm using the shinymaterial R package to make a shiny app and would like to be able to swap tabs programmatically. From this pull request I made the following reprex but I can't get the functionality to work.

How can I adapt the below example to change tabs programmatically using shinymaterial ?

library(shinymaterial)
library(shiny)

select_material_tab <- function(session, tab_id){
  
  js_code <- paste0('$(\'li.tab a[href$="#', tab_id, '"]:first\').trigger("click");')
  
  session$sendCustomMessage(
    type = "shinymaterialJS",
    js_code
  )

}


ui <- material_page(
  title = "Select Material Tabs",
  material_side_nav(fixed = FALSE, tags$h3("Side-Nav Content")),
  material_tabs(
    tabs = c( "First Tab" = "first_tab", "Second Tab" = "second_tab")
  ),
  material_tab_content(
    tab_id = "first_tab", 
    material_button(input_id = "button", label = "GO TO SECOND TAB")
  ),
  material_tab_content(
    tab_id = "second_tab", 
    tags$h1("Second Tab Content")
  )
)

server <- function(input, output, session) {
  observe({
    if (input$button != 0) 
      select_material_tab(session, "second_tab")
  })
}

shinyApp(ui = ui, server = server)
library(shiny)
library(shinymaterial)

js <- "
$(document).on('shiny:connected', function() {
  Shiny.addCustomMessageHandler('selectTab', function(tab) {
    var tabs = document.querySelector('ul.tabs');
    var instance = M.Tabs.getInstance(tabs);
    instance.select(tab);
  });
});
"

ui <- material_page(

  tags$head(tags$script(HTML(js))),
  
  title = NULL,
  
  # Define tabs
  material_tabs(
    tabs = c(
      "First Tab" = "first_tab",
      "Second Tab" = "second_tab",
      "Third Tab" = "third_tab"
    )
  ),
  # Define tab content
  material_tab_content(
    tab_id = "first_tab",
    tags$h1("First Tab Content"),
    material_button("btn1", "Go to tab 2")
  ),
  material_tab_content(
    tab_id = "second_tab",
    tags$h1("Second Tab Content"),
    material_button("btn2", "Go to tab 3")
  ),
  material_tab_content(
    tab_id = "third_tab",
    tags$h1("Third Tab Content"),
    material_button("btn3", "Go to tab 1")
  )
)

server <- function(input, output, session) {
  
  observeEvent(input[["btn1"]], {
    session$sendCustomMessage("selectTab", "second_tab")
  }, ignoreInit = TRUE)  

  observeEvent(input[["btn2"]], {
    session$sendCustomMessage("selectTab", "third_tab")
  }, ignoreInit = TRUE)  

  observeEvent(input[["btn3"]], {
    session$sendCustomMessage("selectTab", "first_tab")
  }, ignoreInit = TRUE)  
  
}

shinyApp(ui = ui, server = server)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM