Search code examples
rshinyreactablehtmltools

R Shiny Add Icon To tag$button


I'm trying to render a table in R Shiny that has a name, file, or url with a download button column that opens a new tab based on the data in the row. I'm unable to have the htmltools tag show an icon in the function that creates the button.

A second question is - why does using mutate to crate this download button column not work but using lapply does? See comment in code.

Here is a minimal example. Instead of a download url this example links to a wiki page.

library(shiny)
library(tidyverse)
library(reactable)

# Functions & Data
DF = data.frame(Targets = letters[1:4])

createLink = function(X) {
    glue::glue("https://en.wikipedia.org/wiki/{X}")
}


buttonOpenURL <- function(X) {
    as.character(htmltools::tags$div(htmltools::tags$button(
        icon = icon("download"),
        # HTML('<i class="fa fa-home"></i>')
        onClick = sprintf("window.open('%s', '_blank')", X)
        
    )))
}

# UI
ui <- fluidPage(
    reactable::reactableOutput("Table")
)

# Server
server <- function(input, output, session) {
    
    DF = data.frame(Targets = letters[1:4]) %>%
        mutate(Download = createLink(Targets)#,
               #Download = as.character(buttonOpenURL(Download))
               # ^^ Why doesn't this work
               ) 
    
    DF$Download = as.character(lapply(DF$Download, buttonOpenURL)) # <- This does work!
    
    output$Table <- reactable::renderReactable(
        reactable::reactable(
            DF,
            columns = list(
                Download = reactable::colDef(sortable = FALSE,
                                             html = TRUE)
            )
        )
    )
}
shinyApp(ui, server)

This code was adapted from here: https://www.r-bloggers.com/2023/04/how-to-use-buttons-in-a-reactable-widget-for-navigation-in-a-shiny-application/

Thanks!


Solution

  • To add an icon in this case use the Unicode character.

    htmltools::tags$span("\u2913"),
    

    Probably obvious for many, but maybe this will help another R user.

    Here is a link to search through Unicodes: https://www.fileformat.info/info/unicode/char/search.htm