PetitJean
PetitJean

Reputation: 1778

R shiny dashboard: generate full UI from server

The first MWE below generates an empty Shiny dashboard application:

library(shiny)
library(shinydashboard)

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody()

ui1 <- dashboardPage(header, sidebar, body)

server <- function(input, output){}

shinyApp(ui = ui1, server = server)

I'm trying to generate the same UI page but dynamically from the server side, as done in the second example below where the second page is displayed only when the correct password is written. It works, however the page design is gone:

library(shiny)
library(shinydashboard)

# UI1 ####
ui1 <- fluidPage(
  textInput('password', label = 'Say hello')
)

# UI2 ####
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody()
ui2 <- dashboardPage(header, sidebar, body)

# Server ####
server <- function(input, output){
  status <- reactiveValues(logged = F)

  observeEvent(input$password,{
    if(input$password == 'hello'){
      status$logged <- T
    }
  })

  output$uipage <- renderUI({
    if(status$logged){
      ui2
    } else {
      ui1
    }
  })
}

# UI ####
ui <- uiOutput("uipage")

shinyApp(ui = ui, server = server)

Any idea how to solve this behaviour?

Upvotes: 0

Views: 705

Answers (1)

user5249203
user5249203

Reputation: 4648

You cannot have 2 ui's (as far as I understand), but you can change part of it. For instance, the dashboard body. I hope this solutions works. If you are trying to have a login page, you probably would like to look at this and this

library(shiny)
library(shinydashboard)

# Ui ####
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(uiOutput("uipage"))
ui <- dashboardPage(header, sidebar, body)

# Server ####
server <- function(input, output) {
    output$uipage <- renderUI({
        fluidPage(
            textInput('password', label = 'hello')
        )
    })

    observeEvent(input$password,{
        if(input$password == 'hello'){
            output$uipage <- renderUI({
                fluidPage(
                selectInput('enter', label = 'Say hello',choices = c("hello","world"))
                )
            })
        }
    })
}
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions