Modify CSS from Shiny reactive output

I have a navbarPage in Shiny where i initialize a tab (let's call it tab1) hidden using css. To achieve that, i use the following line:

tags$head(tags$style(HTML("#tabs li a[data-value = 'tab1'] {display: none;}"))),

Which works perfect.

Now, in the server, i want to show that tab in response to an event, but i don't know how to "update/replace" that css property (display:none) from the R code. I saw that with runjs() can be done, but i'm not really an expert in js/css.

How can i modify that css property for that object in the server?

Hi,

Shiny has some built in ways of hiding and showing tabs. Take a look at this example:

library(shiny)

ui <- fluidPage(
  tabsetPanel(id = "tabSet",
    tabPanel(value = "tab1", title = "Tab 1", tags$h1("TAB 1 content ..."),
             actionButton("toggleTab", "Show tab 2")),
    tabPanel(value = "tab2", title = "Tab 2", tags$h1("TAB 2 content ...")),
    tabPanel(value = "tab3", title = "Tab 3", tags$h1("TAB 3 content ..."))
  )
)

server <- function(input, output, session) {
  hideTab("tabSet", "tab2")
  
  observeEvent(input$toggleTab, {
    if(input$toggleTab %% 2 == 0){
      hideTab("tabSet", "tab2")
      updateActionButton(session, "toggleTab", label = "Show tab 2")
    } else {
      showTab("tabSet", "tab2")
      updateActionButton(session, "toggleTab", label = "Hide tab 2")
    }
  })
}

shinyApp(ui, server)

You need to give every tabsetPanel an ID, and then each tab a value. You can then hide or show a tab with the hideTab() or showTab() function respectively, where you refer to the tabset id and the panel value.

Note that we start with tab 2 in a hidden state by putting hideTab("tabSet", "tab2") at the start of the server code.

In the example, a button will hide or show the tab depending on its state. I used the counter that comes with the button to keep track of the tab being in a hidden state or not.

Hope this helps,
PJ

That doesn't modify the css property for the element, it uses a pure js method, which is not what i asked. But don't worry, i already got it solved. Thanks!

Hi,

Would you please share the solution with us so others can benefit from the answer?

Thanks!
PJ

Using:

addClass(selector = "#tabs li a[data-value = tab1]",class = 'showtab')

Worked Perfectly. Pure JS solution wasn't what i needed because JS is executed at the server after rendering the UI, so, it doesn't render the element hidden, but rather render it visible and then hides it.

2 Likes

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.