Search code examples
rshinyreactable

In R reactable how to add png image on cells column


I would like to add a image (local file) inside the first column of my table with reactable. Bellow is my code: Any help?

data <- data.frame(
  Animal = c("beaver", "cow", "wolf", "goat"),
  Body = c(1.35, 465, 36.33, 27.66),
  Brain = c(8.1, 423, 119.5, 115)
)

reactable(data, columns = list(
  Animal = colDef(cell = function(value) {
    # image <- tags$img(src = "img/icons_flags/Africa.png", width = '18px', height = '18px')
    tagList(
      tags$img(src = "img/icons_flags/Africa.png", width = '18px', height = '18px'),
      value
    )
  }),
  Body = colDef(name = "Body (kg)"),
  Brain = colDef(name = "Brain (g)")
))

Solution

  • Following Inline embedded images and using knitr::image_uri you could do:

    data <- data.frame(
      Animal = c("beaver", "cow", "wolf", "goat"),
      Body = c(1.35, 465, 36.33, 27.66),
      Brain = c(8.1, 423, 119.5, 115)
    )
    
    library(reactable)
    library(htmltools)
    
    img <- tempdir()
    download.file("https://www.r-project.org/logo/Rlogo.png", file.path(img, "logo.png"))
    
    reactable(data, columns = list(
      Animal = colDef(cell = function(value) {
        img_src <- knitr::image_uri(file.path(img, "logo.png"))
        tagList(
          tags$img(src = img_src, width = '18px', height = '18px'),
          value
        )
      }),
      Body = colDef(name = "Body (kg)"),
      Brain = colDef(name = "Brain (g)")
    ))