Shiny: Server-side selectInput values

Hi.

I am trying to add values to selectInput based on distinct values found in the dataframe. I found one way using uiOutput in the server function and renderUI on UI side. See example:

server <- function(input, output, session) {
  data("mtcars")
  output$select_cars = renderUI({
    selectInput("cyl",
                label = "Select cylinder",
                choices = mtcars %>% distinct(cyl) %>% pull %>% append("All", after = 0))
  })
}

ui = fluidPage(
  uiOutput("select_cars")
)

shinyApp(ui, server)

I am wondering whether a better option shouldn't be just plug output values to selectInput rendered on UI side (I do not have an example for this cause I am having trouble figuring it out). So the questions are: Is there an elegant way to do this as described? What are the best practices? Is there any speed difference between these two options?

Thank you!

Hi,

Shiny has an update function for every type of input. It's just the name of the UI element with a prefix of "update". So selectInput --> updateSelectInput.

See example:

library(shiny)
library(dplyr)

ui <- fluidPage(
  selectInput("myInput", "Choose:", choices = "")
)

server <- function(input, output, session) {
  data("mtcars")
  
  updateSelectInput(session, "myInput", 
                    choices =  mtcars %>% distinct(cyl) %>% 
                    pull %>% append("All", after = 0))
}

shinyApp(ui, server)

Hope this helps,
PJ

1 Like

Thanks, PJ. Works as intended.

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