Finch
Finch

Reputation: 297

How to integrate the Twitter widget into Reactjs?

I want to add the Twitter widget into React, but I don't know where to start or how to do it. I am very new to React JS.

Here is the HTML version of the code:

<div class="Twitter">
  <a class="twitter-timeline" href="https://twitter.com/<%= @artist.twitter %>" data-widget-id="424584924285239296" data-screen-name='<%= @artist.twitter %>'>Tweets by @<%= @artist.twitter %></a>
  <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>

And here is what I have so far:

React.DOM.div
  className: 'Twitter'
  children: [
    React.DOM.a
      className: 'twitter-timeline'
      href: "https://twitter.com/" + artist.twitter
      'data-widget-id': "424584924285239296" 
      'data-screen-name': artist.twitter
      children: 'Tweets by ' + artist.twitter
    React.DOM.script
      children: ...
  ]

I was planning to add the script where the dots (...) are, but that doesn't work. Thank you for your help.

Upvotes: 22

Views: 19096

Answers (10)

Romik Makavana
Romik Makavana

Reputation: 83

I knows exactly where is the problem, first you need to understand how does react works. React is frontend framework, works like all DOM is handled by react, if we directly integrate with DOM then sometimes it very difficult to code, cos React is also Updating that DOM.

As per the Twitter documentation, we cannot add twitter.js after init of web page. https://dev.twitter.com/web/javascript/initialization

so it better to use some package, react-twitter-embed

Simple step

npm install --save react-twitter-embed
import { TwitterTimelineEmbed } from 'react-twitter-embed';
<TwitterTimelineEmbed 
    sourceType="profile" 
    userId={"1029587508445630465"} 
    options={{height: 400}} 
/>

You can check other than timeline integration also using package.

https://romik-mk.medium.com/embed-twitter-timeline-widgets-reactjs-a27cafd7cfb6

Upvotes: 0

accimeesterlin
accimeesterlin

Reputation: 4718

Try to install the react-twitter-embed by doing npm install react-twitter-embed. Once installed, the usage is pretty simple. Take a look at the screenshot below.

enter image description here

Code Sample:

import React from 'react';

import { TwitterTimelineEmbed } from 'react-twitter-embed';

const TwitterTimeLine = () => {

  return (
    <TwitterTimelineEmbed
      sourceType="profile"
      screenName="accimeesterlin" // change to your username
      options={{height: 1200}}
    />
  );
}

export default TwitterTimeLine;

They also have a list of other components that you can use as well.

List of available components

  • TwitterShareButton
  • TwitterFollowButton
  • TwitterHashtagButton
  • TwitterMentionButton
  • TwitterTweetEmbed
  • TwitterMomentShare
  • TwitterDMButton
  • TwitterVideoEmbed
  • TwitterOnAirButton

Here is a link to the npm package https://www.npmjs.com/package/react-twitter-embed

Upvotes: 3

Jurosh
Jurosh

Reputation: 7767

There are few interesting solutions out there, but all of those are injecting twitters code to website.

What would I suggest is to create another empty html file just for this widget. Eg. /twitter.html, where you can place all dirty JavaScripts and render widget.

Then when you include:

<iframe src="/twitter.html" />

It will work without any issues. Plus, you have separated external scripts - so it's good for security.

Just add some styling to make it look fine:

twitter.html

html,
body {
  margin: 0;
  padding: 0;
}

React's iframe

iframe {
  border: none;
  height: ???px;
}

Upvotes: 0

Abhay
Abhay

Reputation: 397

You can use this React Social Embed Component.

Disclaimer: It is a component created by me.

Install by: npm i react-social-embed.

Usage:

import TweetEmbed from 'react-social-embed'

<TweetEmbed id='789107094247051264' />
/>

Upvotes: 1

balu
balu

Reputation: 3689

It seems to be much easier to just use Twitter's widgets.js, more specifically createTimeline.

class TwitterTimeline extends Component {
  componentDidMount() {
    twttr.ready(() => {
      twttr.widgets.createTimeline(widgetId, this.refs.container)
    })
  }

  render() {
    return <div ref="container" />   
  }
}

You can load the library directly from https://platform.twitter.com/widgets.js, but they recommend the following snippet:

<script>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"));</script>

More information on setting up the library is here.

Upvotes: 4

Tineo
Tineo

Reputation: 519

class TwitterShareButton extends React.Component {
      render() {
        return <a href="https://twitter.com/share" className="twitter-share-button">Tweet</a>
      }

      componentDidMount() {
        // scriptタグが埋め込まれた後にTwitterのaタグが置かれても機能が有効にならないので、すでにscriptタグが存在する場合は消す。
        var scriptNode = document.getElementById('twitter-wjs')
        if (scriptNode) {
          scriptNode.parentNode.removeChild(scriptNode)
        }

        // ボタン機能の初期化(オフィシャルのボタン生成ページで生成されるものと同じもの)
        !function(d,s,id){
          var js,
              fjs=d.getElementsByTagName(s)[0],
              p=/^http:/.test(d.location)?'http':'https';
          if(!d.getElementById(id)){
            js=d.createElement(s);
            js.id=id;
            js.src=p+'://platform.twitter.com/widgets.js';
            fjs.parentNode.insertBefore(js,fjs);
          }
        }(document, 'script', 'twitter-wjs');
      }

http://qiita.com/h_demon/items/95e638666f6bd479b47b

Upvotes: 1

Dan
Dan

Reputation: 801

This works for me!

Please note that I use React v0.14 and ECMAScript 2015 (aka ES6) with Babel.

index.html (after body tag):

<script>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"));
</script>

Twitter component:

const Twitter = () => (
  <a href="https://twitter.com/your-twitter-page"
    className="twitter-follow-button"
    data-show-count="false"
    data-show-screen-name="false"
  >
  </a>
);

Some React Component (that uses Twitter button):

class SomeReactComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <Twitter />
      </div>
    );
  }
}

Or if you want to have a customized button, you can simply do this:

const Twitter = () => (
  <a href="https://twitter.com/intent/tweet?via=twitterdev">
    <i className="zmdi zmdi-twitter zmdi-hc-2x"></i>
  </a>
);

Upvotes: 6

Raja Rao
Raja Rao

Reputation: 5885

First load Widget JS in your index.html(before your React scripts). Then in your component, simply do the following. The widget JS will rescan the DOM.

componentDidMount: function() {
  twttr.widgets.load()
}

See: https://dev.twitter.com/web/javascript/initialization

Upvotes: 21

Kayo
Kayo

Reputation: 189

It's easy, all you need just use React's componentDidMount hook

{createClass, DOM:{a}} = require "react"

@TwitterWidget = createClass
  componentDidMount: ->
    link = do @refs.link.getDOMNode
    unless @initialized
      @initialized = yes
      js = document.createElement "script"
      js.id = "twitter-wjs"
      js.src = "//platform.twitter.com/widgets.js"
      link.parentNode.appendChild js

  render: ->
    {title, content, widget} = @props
    a
      ref: "link"
      className: "twitter-timeline"
      href: "https://twitter.com/#{widget.path}"
      "data-widget-id": widget.id,
      widget.title

TwitterWidget
  widget:
    id: "your-widget-id"
    title: "Your Twitts"
    path: "widget/path"

Upvotes: 3

Nicol&#242; Taddei
Nicol&#242; Taddei

Reputation: 96

IMHO you should split it down in two. A part of your code could be somehow rendered in a React component

/**
 * @jsx React.DOM
 */
var React = require('react');
var twitterWidget = React.createClass({
    render: function () {
        return (
            <div class="Twitter">
                <a class="twitter-timeline" 
                   href={this.props.link} 
                   data-widget-id={this.props.widgetId} 
                   data-screen-name={this.props.screenName} > 

                   Tweets by {this.props.screenName}
                </a>
            </div>
        );
    }
});
React.renderComponent(<twitterWidget link="..." widgetId="..." />, document.getElementById('containerId');

Your script tag could be placed, as a separate React component or as normal HTML just above the closing body tag.

Upvotes: 1

Related Questions