Adding an image to Shiny action button

Here is another simple solution that worked for me:

actionButton(inputId = "A.button", label = NULL, style = "width: 50px; height: 50px;
background: url('MyImage.png');  background-size: cover; background-position: center;")

the image should be in the www folder inside the app's folder, background size in this case fits image to button size, alternatively you can use background-repeat: no-repeat; to make sure the image is not repeated to fill size, center center should center the image vertically and horizontally.

One could in principle also put the image as label, like:

label = img (src="MyImage.png", width="30", height="30"),

However, then the image could stuck out over the edge of the button compared to inserting it as background.


That's pretty easy with the argument icon of the function actionButton():

actionButton("goButton", "", icon = icon("play-circle"))

Alternatively, you can use the function icon() to add an icon to your button code:

tags$button(
          id = "reset_button",
          class="btn action-button",
          icon("close")

        )

Or you use the img() function to use your own:

    tags$button(
      id = "web_button",
      class = "btn action_button",
      img(src = "http://www.craftech.com/wp-uploads/2015/05/web.png",
               height = "50px")
    )

To get a more comprehensive list of possible icons, take a look at ?icon help page of the shiny package and the links in the See Also section.

An example app:

shinyApp(
  ui = shinyUI(
    fluidPage(
      fluidRow(
        actionButton("goButton", "", icon = icon("play-circle")),
        tags$button(
          id = "reset_button",
          class="btn action-button",
          icon("close")

        ),
        tags$button(
          id = "web_button",
          class = "btn action-button",
          tags$img(src = "http://images.all-free-download.com/images/graphicthumb/button_play_89677.jpg",
                   height = "50px")
        )
      ),
      fluidRow(
        textOutput("text")
      )
    )
  ),
  server = function(input, output, session){
    out <- reactiveVal("Nothing")
    observeEvent(input$goButton,{
      out("Go Pushed")
    })
    observeEvent(input$reset_button,{
      out("Resetted")
    })
    observeEvent(input$web_button,{
      out("From the web")
    })
    output$text <- renderText({out()})
  }
)

Tags:

R

Shiny