Embed Twitter feed in React

The snippet works by loading some javascript and updating an HTML element with the feed. If you’re using this in a single page app with React this can be a problem. We only want to load the javascript once instead of every time our component renders.

It’d be better to move the script to the end of our body tag (so rendering isn’t blocked). This is fine for the first time the page loads. What if you render a twitter component after the initial load?

Twitter makes it easy to load widgets after the initial load.

twttr.widgets.load(document.getElementById(‘twitter-timeline’)); 1 twttr.widgets.load(document.getElementById(‘twitter-timeline’)); We could take this function call and put it in our componentDidMount lifecycle method. We also need to make sure we don’t try and use the twttr variable before the script loads.

A basic react component to load a twitter feed could then look something like this.

class TwitterFeed extends React.Component<{}>{
  componentDidMount() {
    if (typeof twttr !== 'undefined') {
  render() {
    return <a id="twitter-feed" className="twitter-timeline" data-height="600" data-theme="dark" href="https://twitter.com/some_url_here"></a>


I do some software development

Read More