Closed cpx2017 closed 2 years ago
+1, unusable in React 17
For those that might stumble upon this, I didn't need anything fancy and needed a simple Tweet embed component, so wrote my own quick and dirty implementation. Sharing it with you all. Performance looks okay (not duplicating requests). Works in React 17+.
Step 1: Save the Twitter widget in a file twitterWidget.js Code from: Twitter Dev
const twitterWidget = () => {
window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
}
export default twitterWidget
Step 2: Save the component TweetEmbed.js Note: You can configure the options to your own liking, listed here: Twitter dev
import { useState, useEffect } from 'react'
import twitterWidget from '../../extra/twitterWidget'
const TweetEmbed = ({ tweetId = '' }) => {
const [widget, setWidget] = useState()
const [twt, setTwttr] = useState()
const [loading, setLoading] = useState(true)
// Make sure we have a window before attaching the twitter widget
useEffect(() => {
if(typeof window !== 'undefined') {
setWidget(twitterWidget())
if(window.twttr) {
setTwttr(window.twttr)
}
}
}, [widget])
// Check to make sure the widgets library is loaded
useEffect(() => {
if (twt) {
const interval = setInterval(() => {
const loaded = twt.init
if (loaded) {
setLoading(false)
clearInterval(interval)
}
}, 500)
}
}, [twt])
// Spawn in the actual tweet
useEffect(() => {
if (!loading) {
// Options for embedding can be found here
// https://developer.twitter.com/en/docs/twitter-for-websites/embedded-tweets/guides/embedded-tweet-parameter-reference
twt.widgets.createTweetEmbed(tweetId, document.getElementById(tweetId),
{
theme: 'light',
align: 'center',
// Min 220px, Max 550px
width: '550px'
}
)
.then(d => console.log(`Loaded Tweet ${tweetId} successfully.`))
.catch(e => console.log(`Failed to load Tweet ${tweetId}.`))
}
}, [loading])
return (
<div id={tweetId} />
)
}
export default TweetEmbed
Step 3: Use the TweetEmbed
Component by passing in Tweet ID
<TweetEmbed tweetId='1482862566028107778' />
New version deployed. it will support react 17 with hooks. 👍
I use React 17.0 and I cannot downgrade because another library version affect reason. Can you update library support to target version?