forked from capaj/react-tweet-embed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tweet-embed.js
62 lines (53 loc) · 1.45 KB
/
tweet-embed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import React from 'react'
import PropTypes from 'prop-types'
const callbacks = []
function addScript (src, cb) {
if (callbacks.length === 0) {
callbacks.push(cb)
var s = document.createElement('script')
s.setAttribute('src', src)
s.onload = () => callbacks.forEach((cb) => cb())
document.body.appendChild(s)
} else {
callbacks.push(cb)
}
}
class TweetEmbed extends React.Component {
componentDidMount () {
const renderTweet = () => {
window.twttr.ready().then(({ widgets }) => {
const { options, onTweetLoadSuccess, onTweetLoadError } = this.props
widgets
.createTweetEmbed(this.props.id, this._div, options)
.then(onTweetLoadSuccess)
.catch(onTweetLoadError)
})
}
if (!window.twttr) {
const isLocal = window.location.protocol.indexOf('file') >= 0
const protocol = isLocal ? this.props.protocol : ''
addScript(`${protocol}//platform.twitter.com/widgets.js`, renderTweet)
} else {
renderTweet()
}
}
render () {
return <div className={this.props.className} ref={(c) => {
this._div = c
}} />
}
}
TweetEmbed.propTypes = {
id: PropTypes.string,
options: PropTypes.object,
protocol: PropTypes.string,
onTweetLoadSuccess: PropTypes.func,
onTweetLoadError: PropTypes.func,
className: PropTypes.string
}
TweetEmbed.defaultProps = {
protocol: 'https:',
options: {},
className: null
}
export default TweetEmbed