Cesar Jr Rodriguez
Cesar Jr Rodriguez

Reputation: 1821

How can I format embeded tweets using ReactJs?

I'm receiving a document from the server that receives an embeded tweet and injecting it this way:

renderDetails() {
  return (
    <div className="new-content">
      <h1 className="title-new">{this.state.new.title}</h1>
      <div className="body-new" 
        dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(this.state.new.content)}}
      ></div>
    </div>
  );
}

The content has this form:

<div class="new-content">
.
.
.
<blockquote>America(@VOANoticias)&nbsp;<a href="https://twitter.com/VOANoticias/status/1110915154106085377?ref_src=twsrc%5Etfw">27 de marzo de 2019</a></blockquote>
.
.
.

How can I process this data to show the blockquote formatted as a tweet?

Upvotes: 0

Views: 52

Answers (1)

Agney
Agney

Reputation: 19224

You can pick the tweet-id from the anchor tag and use it to create the tweet programmatically.

const twitterItems = Array.from(document.querySelectorAll("a[href^='https://twitter.com']"));

twitterItems.forEach((item) => {
  const extractedUrlStr = item.href;
  const url = new URL(extractedUrlStr);
  const tweetID = url.pathname.split("/")[3];
  const parentQuote = item.parentNode;
  parentQuote.innerHTML = "";
  twttr.widgets.createTweet(tweetID, parentQuote);
});

For React, you would probably insert this code in componentDidMount

PS: If the blockquote is of correct defined format, just including the script in the document will format the tweet for you.

Codepen Demo

Upvotes: 1

Related Questions