javascriptcssrshinybslib

How to change CSS classes and style for nav tabs after bslib nav_insert?


Currently for the bslib package, a nav_insert() into a page_navbar does not pass along the same CSS classes as it does for a regular tab-pane, as noted in this issue posted to the bslib Github repo.

The reprex provided by the OP is the following:

library(shiny)
library(bslib)

ui <- page_navbar(
  id = 'nav',
  nav_panel('Page 1',
            card("Content 1")))

server <- function(input, output, session) {
  nav_insert(id = "nav",
             nav = nav_panel('Page 2',
                             card("Content 2")))
}

shinyApp(ui, server)

The newly inserted tab "Page 2" does not have the same css classes as the "Page 1" tab, namely html-fill-item html-fill-container bslib-gap-spacing.

Is there a way, perhaps, to add those classes after the insert? I tried using runjs($('[data-value=Page 1]').addClass('html-fill-item')) (and several iterations of it) in the server but that did not work.

A very trivial JSFiddle demo shows the idea of the basic working syntax.


Solution

  • You can pass the class and style explicitly to nav_panel.

    enter image description here

    library(shiny)
    library(bslib)
    
    ui <- page_navbar(
        id = 'nav',
        nav_panel('Page 1',
                  card("Content 1")))
    
    server <- function(input, output, session) {
        nav_insert(id = "nav",
                   nav = nav_panel('Page 2',
                                   class = "html-fill-item html-fill-container bslib-gap-spacing",
                                   style = "--bslib-navbar-margin:0;",
                                   card("Content 2")))
    }
    
    shinyApp(ui, server)