Search code examples
rshinyshinywidgets

Adding country flag to pickerinput shinywidgets


There is a example how to add country flags to checkBoxGroupInput here

https://gist.github.com/bborgesr/f2c865556af3b92e6991e1a34ced2a4a

I am trying to adjust the code slightly to achieve the same result using pickerinput from shinywidgets. However, in my results I do not see any image.

  library(shiny)
  library(shinyWidgets)

  countries <- c("Australia", "United Kingdom", "United States")

  flags <- c(
    "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/au.svg",
    "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/gb.svg",
    "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/us.svg"
  )

  ui <- fluidPage(

    pickerInput("countries", "countries", multiple = T,
                choices = countries,

                choicesOpt = list(content =  
                                    mapply(countries, flags, FUN = function(country, flagUrl) {
                                      tagList(
                                        tags$img(src=flagUrl, width=20, height=15),
                                        country
                                      )
                                    }, SIMPLIFY = FALSE, USE.NAMES = FALSE)

                                    ))
    ,

  textOutput("txt")
  )

    server <- function(input, output, session) {
    output$txt <- renderText({
      paste("You chose", paste(input$countries, collapse = ", "))
    })
  }

  shinyApp(ui, server)

Solution

  • Hi you don't want to add options as tagList but rather as HTML strings like this

    library(shiny)
    library(shinyWidgets)
    
    countries <- c("Australia", "United Kingdom", "United States")
    
    flags <- c(
      "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/au.svg",
      "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/gb.svg",
      "https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/us.svg"
    )
    
    ui <- fluidPage(
    
      pickerInput("countries", "countries", multiple = T,
                  choices = countries,
    
                  choicesOpt = list(content =  
                                      mapply(countries, flags, FUN = function(country, flagUrl) {
                                        HTML(paste(
                                          tags$img(src=flagUrl, width=20, height=15),
                                          country
                                        ))
                                      }, SIMPLIFY = FALSE, USE.NAMES = FALSE)
    
                  ))
      ,
    
      textOutput("txt")
    )
    
    server <- function(input, output, session) {
      output$txt <- renderText({
        paste("You chose", paste(input$countries, collapse = ", "))
      })
    }
    
    shinyApp(ui, server)
    

    Hope this helps!