Created
April 1, 2016 22:55
-
-
Save andrewimm/9fdd0007c3476446986a9f600ba4183f to your computer and use it in GitHub Desktop.
FB Send plugin in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
let fbInjected = false; | |
let fbLoaded = !!window.FB; | |
let fbCallbacks = []; | |
function onFbLoad() { | |
fbLoaded = true; | |
fbCallbacks.forEach((cb) => { | |
cb(); | |
}); | |
} | |
class FBLoader extends React.Component { | |
constructor(props) { | |
super(props); | |
if (fbLoaded) { | |
// Injected and loaded | |
if (props.onFbLoad) { | |
props.onFbLoad(); | |
} | |
} else if (fbInjected) { | |
// Injected but not loaded | |
if (props.onFbLoad) { | |
fbCallbacks.push(props.onFbLoad); | |
} | |
} else { | |
// Not yet injected | |
fbInjected = true; | |
let script = document.createElement('script'); | |
script.onload = onFbLoad; | |
script.src = 'https://connect.facebook.net/es_US/sdk.js#xfbml=1&version=v2.5'; | |
document.body.appendChild(script); | |
} | |
} | |
render() { | |
return React.Children.only(this.props.children); | |
} | |
} | |
class MyComponent extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
fbLoaded: false, | |
}; | |
} | |
componentDidMount() { | |
} | |
componentWillUpdate(_, nextState) { | |
if (nextState.fbLoaded && !this.state.fbLoaded) { | |
window.FB.XFBML.parse(this._scope); | |
} | |
} | |
render() { | |
return ( | |
<div> | |
<FBLoader onFbLoad={() => this.setState({fbLoaded: true})}> | |
<div ref={(s) => this._scope = s}> | |
<div id="fb-root"></div> | |
<div className="fb-send" dataHref="http://www.google.com" dataLayout="button_count" /> | |
</div> | |
</FBLoader> | |
</div> | |
); | |
} | |
} | |
class App extends React.Component { | |
render() { | |
return ( | |
<div> | |
<MyComponent /> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<App />, document.getElementById('mount')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment