简体   繁体   中英

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM