It is highly ironic that there are no react facebook plugins...
I want to show the facebook page plugin on my site (built in React) but nothing shows.
I have the default javascript jargon (I added async
to no avail):
<div id="fb-root"></div>
<script>
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.async=true;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6&appId=";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
And the normal page plugin in the render
of my react component:
<div className="fb-page"
data-href="https://www.facebook.com/facebook/"
data-tabs="timeline"
data-width="500"
data-height="400"
data-small-header="true"
data-adapt-container-width="true"
data-hide-cover="false"
data-show-facepile="false">
<blockquote className="fb-xfbml-parse-ignore"
cite="...
</div>
How can I get this to load async?
The sdk invokes a function after it finished loading the script, called fbAsyncInit
:
window.fbAsyncInit = function () {
FB.init({
appId: '82195',
xfbml: false,
version: 'v2.6'
});
document.dispatchEvent(new Event('fb_init'));
};
As is show, I dispatch an event when the callback is called; as it indicates that the SDK is loaded. Since the problem is that react loads and executes before the sdk, a listener can be added to the component which can then load the FB plugin when notified:
componentDidMount() {
document.addEventListener('fb_init', e => FB.XFBML.parse());
}
This is what you need: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse
For example:
componentDidMount() {
FB.XFBML.parse();
}
componentDidUpdate() {
FB.XFBML.parse();
}
Better give it an ID though, or it will check the whole document for Facebook Plugins. Of course you have to make sure that the JavaScript SDK is loaded already, or "FB" will be undefined. You could implement a timer that checks for the availability of "FB" until it´s available (bad idea), or just load the component later - when the JS SDK is loaded for sure.
More information about checking when the JS SDK is loaded: http://www.devils-heaven.com/facebook-javascript-sdk-login/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With