Shiny dropdown input (selectizeInput) with fontawesome icons
Asked Answered
A

1

5

I want to include font-awesome icons in the items of a Shiny selectizeInput. How could I do?

Apportionment answered 24/7, 2021 at 11:20 Comment(0)
A
6

Here is a function, selectInputWithIcons, that does the job.

enter image description here

library(shiny)
library(fontawesome)
library(htmltools)


selectInputWithIcons <- function(
  inputId, inputLabel, labels, values, icons, iconStyle = NULL,
  selected = NULL, multiple = FALSE, width = NULL
){
  options <- mapply(function(label, value, icon){
    list(
      "label" = label,
      "value" = value,
      "icon"  = as.character(fa_i(icon, style = iconStyle))
    )
  }, labels, values, icons, SIMPLIFY = FALSE, USE.NAMES = FALSE)
  render <- paste0(
    "{",
    "  item: function(item, escape) {", 
    "    return '<span>' + item.icon + '&nbsp;' + item.label + '</span>';", 
    "  },",
    "  option: function(item, escape) {", 
    "    return '<span>' + item.label + '</span>';", 
    "  }",
    "}"
  )
  widget <- selectizeInput(
    inputId  = inputId, 
    label    = inputLabel,
    choices  = NULL, 
    selected = selected,
    multiple = multiple,
    width    = width,
    options  = list( 
      "options"    = options,
      "valueField" = "value", 
      "labelField" = "label",
      "render"     = I(render),
      "items"     = as.list(selected)
    )
  )
  attachDependencies(widget, fa_html_dependency(), append = TRUE)
}


ui <- fluidPage(
  br(),
  selectInputWithIcons(
    "slctz",
    "Select an animal:",
    labels    = c("I want a dog", "I want a cat"),
    values    = c("dog", "cat"),
    icons     = c("dog", "cat"),
    iconStyle = "font-size: 3rem; vertical-align: middle;",
    selected  = "cat"
  )
)

server <- function(input, output, session){
  
  observe({
    print(input[["slctz"]])
  })
  
}


shinyApp(ui, server)
Apportionment answered 24/7, 2021 at 11:25 Comment(2)
Could you please make this work with option groups? shiny.rstudio.com/gallery/…Remediable
@Remediable see <https://mcmap.net/q/2035958/-shiny-dropdown-input-with-groups-decorated-with-icons/1100107>Sudduth

© 2022 - 2024 — McMap. All rights reserved.