Make sidebar tab selected by default in shiny when using renderUI

Viewed 1272

I'm using renderUI for the first time. When I run the app there is no tab selected by default; when defining the UI outside of the server the first tab is normally selected by default.

Any idea why this happens, or how to specify that the first tab should be selected by default on startup?

Example:

library(shiny)
library(shinydashboard)
library(tidyverse)
library(DT)


header <- dashboardHeader(title = "header") 

sidebar <- dashboardSidebar(uiOutput("sidebar"))

body <- dashboardBody(uiOutput("body"))

ui <- dashboardPage(title = 'Radial Networks', header, sidebar, body, skin='blue')

server <- function(input, output, session){

  output$body <- renderUI({
    dashboardBody(
       tabItems(
         tabItem(
           tabName = 'Chords', h2(fluidRow(
             box(plotOutput('plot'), type = 'html',  width = 6, height = '870px')
           )))))})

 output$sidebar <- renderUI({
   dashboardSidebar(sidebarMenu(
     menuItem("Radial Networks", tabName = "Chords", icon = icon("adjust"))))
 })

  output$plot <- renderPlot({
    ggplot(mtcars, aes(x = factor(cyl))) +
      geom_bar()
  })

}

  shinyApp(ui = ui, server = server)
1 Answers

Try adding one argument to your tabItem():

library(shiny)
library(shinydashboard)
library(tidyverse)
library(DT)


header <- dashboardHeader(title = "header") 

sidebar <- dashboardSidebar(uiOutput("sidebar"))

body <- dashboardBody(uiOutput("body"))

ui <- dashboardPage(title = 'Radial Networks', header, sidebar, body, skin='blue')

server <- function(input, output, session){

  output$body <- renderUI({
    dashboardBody(
       tabItems(
         tabItem(
           tabName = 'Chords', 
                        h2(fluidRow(box(plotOutput('plot'), 
                        type = 'html',  
                        width = 6, 
                        height = '870px')
           )))))})

 output$sidebar <- renderUI({
   dashboardSidebar(sidebarMenu(
               menuItem("Radial Networks", 
                     tabName = "Chords", 
                     icon = icon("adjust"),
                     selected = 1)))
 })

  output$plot <- renderPlot({
    ggplot(mtcars, aes(x = factor(cyl))) +
      geom_bar()
  })

}

  shinyApp(ui = ui, server = server)
Related