How to integrate the Twitter widget into Reactjs?

2019-04-03 15:36发布

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.

8条回答
The star\"
2楼-- · 2019-04-03 15:56

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.

查看更多
We Are One
3楼-- · 2019-04-03 15:58

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;
}
查看更多
登录 后发表回答