Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate table and clickable images in Shiny R

I need to do the following in R:

1) Dynamically(for X images in ...) create a table/grid where I display them, for example in a 4xN table.

2) Make each of those images clickable, so that it feeds its name into a function in R. For example if we clicked on a monkey, it is supposed to call a function: selected(monkey.jpg).

like image 822
user1577191 Avatar asked Nov 24 '25 19:11

user1577191


1 Answers

Feels like cheating but using a little JS is the easiest way.

In your ui.R, put this somewhere (like inside your mainPanel or whatever):

uiOutput("imageGrid"),
tags$script(HTML(
  "$(document).on('click', '.clickimg', function() {",
  "  Shiny.onInputChange('clickimg', $(this).data('value'));",
  "};"
))

In your server function:

output$imageGrid <- renderUI({
  fluidRow(
    lapply(images, function(img) {
      column(3, 
        tags$img(src=paste0("images/", img), class="clickimg", data-value=img)
      )
    })
  )
})

Then in your server function you can access input$clickimg to determine the last clicked images. Keep in mind this'll be a reactive value (just like any other input), so you have to access it from within a reactive expression or output rendering function (or observer if you're a more advanced Shiny user). Oh and the initial value will be NULL so don't forget to check for that too.

like image 83
Joe Cheng Avatar answered Nov 26 '25 07:11

Joe Cheng