R Shiny variable ordered or unordered list

3.6k views Asked by At

I would like to use an ordered/unordered list such as the following:

tags$ul(
    tags$li("Item 1"),
    tags$li("Item 2"),
    tags$li("Item 3"),
    tags$li("Item 4")
)

However, I would like the number of items in the list to be dependent on some other factor; that is, not of fixed size. Is this possible?

For example, if my character vector ends up being size 3, then I want to display the three elements in it as three separate rows. If the vector is size 10, then it should be an ordered/unordered list with 10 levels.

So asking for two things here:

  1. Make the ordered/unordered list of varying size depending on some variable
  2. Display certain text in each of the levels that also varies depending on which rows are shown
1

There are 1 answers

1
divibisan On

Shiny is smart enough that if you pass a list of HTML tags to a uiOutput it will put each of them on a separate line in the automatically generated HTML code. So, you can use apply to make a list of tags$li objects, then pass them to a uiOutput to display them on your page:

library(shiny)

ui <- fluidPage(
    tags$ul(
        uiOutput('list')
    )

)

server <- function(input, output, session) {
  df <- data.frame(item = c('item 1', 'item 2', 'item 3'), num = c(2,3,4))

  output$list <- renderUI({
        apply(df, 1, function(x) tags$li(x['item'], "The SCORE IS: ", x['num']))
  })
}

shinyApp(ui, server)

You can expand this however you want. As long as the function in the apply returns a tags$li object, you can make it as complex as you'd like.