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:
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"
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
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>
);