Embed twitter tweet in shiny app

Hi all

I would like to embed a tweet in my shiny app and when someone clicks on the tweet it redirects them directly to the original tweet in twitter.

Here is an app created by @nsgrantham were part of his app is doing so:
https://nsgrantham.shinyapps.io/tidytuesdayrocks/

I tried to write the following code, but it did not work for me:


ui <- fluidPage(

  titlePanel("SMT"),

  uiOutput("tweet")
)

server <- function(input, output) {

  output$tweet <-   renderUI({
    
    tags$blockquote(class = "twitter-tweet", 
                    tags$a(href = "https://twitter.com/SudanPMHamdok/status/1222920158764728327"))
  }) 

}

My apologize if I did not report the issue correctly, it's my first time I post an issue.

Hi @Momen. You have to run the widgets.js from twitter first and load the widget by twttr.widgets.load.

library(shiny)
library(tidyverse)

ui <- fluidPage(
  tags$head(
    tags$script(async = NA, src = "https://platform.twitter.com/widgets.js")
  ),
  titlePanel("SMT"),
  uiOutput("tweet")
)

server <- function(input, output) {
  
  output$tweet <-   renderUI({
    tagList(
      tags$blockquote(class = "twitter-tweet",
                      tags$a(href = "https://twitter.com/SudanPMHamdok/status/1222920158764728327")),
      tags$script('twttr.widgets.load(document.getElementById("tweet"));')
    )
  })
}

shinyApp(ui, server)

Thank you very much!

It worked perfectly!

Is there a possibility to explain the solution?

@Momen. For loading twitter, first of all you have to load the widgets.js from the platform.twitter.com. However, because the tweet ui is dynamically construct, it did not exist during page load. If you run twttr.widgets.load from the head, it will not load the tweet content. So, you have to dynamically load the twttr.widgets.load at the time the tweet content ready.

1 Like

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.