Facebook SDK with React Web

Viewed 2890

Has anyone had success using the Facebook SDK in your react web (not native) project? There doesn't seem to be any good documentation on it.

Specifically. Where to I call the init function?

 <script>
 window.fbAsyncInit = function() {
 FB.init({
  appId            : 'your-app-id',
  autoLogAppEvents : true,
  xfbml            : true,
  version          : 'v2.9'
});
FB.AppEvents.logPageView();
};

(function(d, s, id){
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) {return;}
 js = d.createElement(s); js.id = id;
 js.src = "//connect.facebook.net/en_US/sdk.js";
 fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));
 </script>

If I add it on every page, FB.AppEvents.logPageView() does not load/register back to Facebook ( I don't see it when debugging events). If I add the init code on my main app.js, and then just add FB.AppEvents.logPageView() on individual pages I sometimes get an console error that FB.AppEvents can't be found.

What is the best practice for integrating the Facebook SDK in a react web app?

2 Answers

There may be many approaches, I am currently using that approach to do this:

  • Add the Facebook SDK for JavaScript in index.html page where you are placing your whole app component. Also add <div id="fb-root"></div> after the start of body tag in the same index.html file.

<body><div id="fb-root"></div><div id="root"></div>

 <script>
 window.fbAsyncInit = function() {
 FB.init({
  appId            : 'your-app-id',
  autoLogAppEvents : true,
  xfbml            : true,
  version          : 'v2.9'
});
FB.AppEvents.logPageView();
};

(function(d, s, id){
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) {return;}
 js = d.createElement(s); js.id = id;
 js.src = "//connect.facebook.net/en_US/sdk.js";
 fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));
 </script></body>
  • The above snippet initialises the window.FB variable once your app component mounted. You can use this variable to do window.FB.AppEvents.logPageView() and any other stuff such as accessing graph API.
  • There is one issue that can be arises and that is when the component is mounted, things works fine, but once, its un-mounted and you can come back to this component, things may not work fine such as fb comments or like plugin. To tackle this issue you have to put the following line: if (window.FB) {window.FB.XFBML.parse();} in ComponentDidMount() life cycle method of every component in which you are accessing facebook stuff. It will re-parse the dom after mounting your component.
Related