KonstantinosM KonstantinosM - 2 months ago 21
R Question

Show tabPanel dynamically in Shiny

I am using Shiny and I am trying to make a set of

tabPanels
appear dynamically based on a set of parameters. In the code below, I would like to make the first tabPanel appear only when
showTab1 <- T
and so on.

I tried with simple if statements and conditionalPanels but it fails. Below there is an example of code:

rm(list = ls())
library(shiny)
library(shinydashboard)

showTab1 <- T
showTab2 <- F
showTab3 <- T


ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(

),
dashboardBody(
uiOutput("tabs")
)
)
server <- function(input, output) {

output$tabs <- renderUI({


tabBox(width = 1000,height = 500,

if (showTab1 == T) { tabPanel("tab1") },

if (showTab2 == T) { tabPanel("tab2") },

if (showTab3 == T) { tabPanel("tab3") }

)



})


}

shinyApp(ui, server)


Thanks for your help.

Cheers,
Kostas

Answer

You can dynamically create them:

rm(list = ls())
library(shiny)
library(shinydashboard)

showTab1 <- T
showTab2 <- F
showTab3 <- T

ShowTotal <- which(c(showTab1,showTab2,showTab3))

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(uiOutput("ui"))
)
server <- function(input, output) { 

  output$ui <- renderUI({
    myTabs = lapply(paste('tab', ShowTotal), tabPanel)
    do.call(tabsetPanel, myTabs)
  })
}

shinyApp(ui, server)

enter image description here