Search code examples
rshinyselectinput

use html in selectizeInput with R shiny


I would like to use some html in the choices in select(ize)Input. Does anyone know a simple solution how to tell shiny to treat the options as HTML?

library(shiny)

ui <- fluidPage(
  selectInput("test html use", label = "option", choices = c("<div title = 'This is option A'>opt A</div>", "opt B"))
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)

Solution

  • In order to treat the options of a selectizeInput as HTML, the render option is the way to go. The following code will render the ordinary output:

    library(shiny)
    
    shinyApp(
      ui = fluidPage(
        br(),
        selectizeInput(
          "slctz", "Select something:",
          choices = list("option1" = "value1", "option2" = "value2"), 
          options = list( 
            render = I("{
            item: function(item, escape) { 
              return '<span>' + item.label + '</span>'; 
            },
            option: function(item, escape) { 
              return '<span>' + item.label + '</span>'; 
            }
          }")
          )
        )
      ),
      server = function(input, output) {}
    )
    

    The option field is for the list of options, while the item field is for the selected options.

    So if you want to style the options and the selected options, you can do so cleanly by adding a class attribute to the span elements, and by defining your CSS classes in the UI:

    ui = fluidPage(
      tags$head(
        tags$style(
          HTML(
            "
            .myoption {......}
            .myitem {......}
            "
          )
        )
      ),
      br(),
      selectizeInput(
        "slctz", "Select something:",
        choices = list("option1" = "value1", "option2" = "value2"), 
        options = list( 
          render = I("{
            item: function(item, escape) { 
              return '<span class=\"myitem\">' + item.label + '</span>'; 
            },
            option: function(item, escape) { 
              return '<span class=\"myoption\">' + item.label + '</span>'; 
            }
          }")
        )
      )
    )