I need a dropdown menu that would have certain groups of choices, with the first option being “Use all data”. That choice makes up it’s own option group, and this group doesn’t need a name.
Unfortunately, selectInput() doesn’t allow that. Either all option groups need to be names, or none of them can. I tried to manipulate the tags using htmltools and tagQuery(), but the individual optgroup-header tags cannot be accessed.
A reprex:
library(shiny)
grouped_options <- list(
"Named category 1" =
list(
"list_choice1"
),
# this category shouldn't have a visible name
"NONAME" =
list(
"list_choice2",
"list_choice3"
),
"Named category 2" =
list(
"list_choice5",
"list_choice6"
)
)
dropdown_element <- selectInput(inputId = "dd1",
label = "Dropdown menu with categorised options",
choices = grouped_options)
ui <- fluidPage(
h1("Demo dropdown with categories"),
dropdown_element,
textOutput("sel_choice")
)
)
server <- function(input, output, session) {
output$sel_choice <- renderText(input$dd1)
}
shinyApp(ui, server)
I’ve managed to write up a hack to accomplish this using CSS:
library(shiny)
grouped_options <- list(
"Named category 1" =
list(
"list_choice1"
),
"NONAME" =
list(
"list_choice2",
"list_choice3"
),
"Named category 2" =
list(
"list_choice5",
"list_choice6"
)
)
dropdown_element <- selectInput(inputId = "dd1",
label = "Dropdown menu with categorised options",
choices = grouped_options)
ui <- fluidPage(
h1("Demo dropdown with categories"),
dropdown_element,
textOutput("sel_choice"),
# CSS to reduce font size to invisibility
tags$style(HTML("
div[data-group='NONAME'] > .optgroup-header {
font-size:0px
}
"
))
)
server <- function(input, output, session) {
output$sel_choice <- renderText(input$dd1)
}
shinyApp(ui, server)
The optiongroup named NONAME will have its name written with a font sized 0px, effectively making it invisible. This option group can be placed at any place in the list of options.
One downside – you can only have one optgroup called NONAME. If you require more, you should call new optgroups NONAME2 etc., and duplicate the CSS rule with those names as well.
Hope this helps someone in a similar situation!