Jae Ahn
Jae Ahn

Reputation: 3

tabItem appears when tabName is put in as string, but not as variable in R SHINY

I am trying to create a dashboard with a different body appearing for different tabs. However, the below code does not work. While tabs are created, nothing appears in the tabs. If I change tabName to a string (ex. menuItem(name_dataset[1], tabName = "data1")), the right body contents appear in each tab.

Why is this? Why can I not use a variable for tabName instead of just raw string?

#SHINY DASHBOARD: UI 
header <- dashboardHeader()

sidebar <- dashboardSidebar(
    sidebarMenu(
    menuItem(name_datasets[1], tabName = name_datasets[1]),
    menuItem(name_datasets[2], tabName = name_datasets[2])
    )
)

body <- dashboardBody(
    tabItems(
    #First tab
        tabItem(tabName = name_datasets[1], h2(name_datasets[1])),

    #Second tab
    tabItem(tabName = name_datasets[2], h2(name_datasets[2]))
    )
)

ui <- dashboardPage(header, sidebar, body)

Upvotes: 0

Views: 271

Answers (1)

B&#225;rbara Borges
B&#225;rbara Borges

Reputation: 919

My bet is that your name_datasets vector includes strings with either spaces or some other reserved character. The tabName argument (whether supplied directly or not) should be a simple and unique key, so it shouldn't contain spaces, ampersands, percentages, etc...

You can verify this works without "weird" characters:

library(shiny)
library(shinydashboard)

name_datasets <- c(a = "letter_a1", b = "letter_b2")

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tabs",
    menuItem(name_datasets[1], tabName = name_datasets[1]),
    menuItem(name_datasets[2], tabName = name_datasets[2])
  )
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = name_datasets[1], h2(name_datasets[1])),
    tabItem(tabName = name_datasets[2], h2(name_datasets[2]))
  )
)

ui <- dashboardPage(dashboardHeader(), sidebar, body)
server <- function(input, output, session) {}

shinyApp(ui, server)

However, if you do want to display spaces or dollar signs or something "weird" to the end-user, you can still do that (since tabName is only really used internally). For example, this is a very similar app to the last one, but you'll notice that even though the tabNames are very simple ("a" and "b"), what is displayed to the user both in the sidebar and in the main body is a lot more complex:

library(shiny)
library(shinydashboard)

name_datasets <- c(a = "letter $ % a1", b = "letter b2 % $")

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tabs",
    menuItem(name_datasets[1], tabName = names(name_datasets)[1]),
    menuItem(name_datasets[2], tabName = names(name_datasets)[2])
  )
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = names(name_datasets)[1], h2(name_datasets[1])),
    tabItem(tabName = names(name_datasets)[2], h2(name_datasets[2]))
  )
)

ui <- dashboardPage(dashboardHeader(), sidebar, body)
server <- function(input, output, session) {}

shinyApp(ui, server)

Upvotes: 1

Related Questions