2

I'm trying to add a facebook share to my react application. There is a lot of detail on Stackoverflow around adding FB.XFBML.parse()

How ever i'm a lint error "FB is not defined". What is the best way to load FB?

edit

window.fbAsyncInit function added.

"use strict";

var React = require('react');
var Router = require('react-router');
var Link = Router.Link;
var ThanksPage = React.createClass({
componentDidMount: function() {

            (function (d, s, id) {
            const fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {
              return;
            }
            const js = d.createElement(s); js.id = id;
            js.async = true;
            js.src = '//connect.facebook.net/fr_CA/sdk.js';
            fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));

            window.fbAsyncInit = function() {
                FB.XFBML.parse();
            };


    },
    render: function() {
                    return (
                    );
    }
    });

    module.exports = ThanksPage;
andyrandy
  • 72,880
  • 8
  • 113
  • 130
frosty
  • 5,330
  • 18
  • 85
  • 122
  • did you even initialize the app? FB.init requires some parameters. please optimize the indentation of your code, it´s hard to read right now. – andyrandy Jun 16 '16 at 09:17
  • I've remove the init. The FB examples don't use this. My issue is that lint is saying FB is not defined and i need to work out how to register it with reactjs. – frosty Jun 16 '16 at 09:23

3 Answers3

6

You can only use FB after FB.init:

componentDidMount() {
    window.fbAsyncInit = function() {
        //SDK loaded, initialize it
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            version    : 'v2.6'
        });
        //JS SDK initialized, now you can use it
        FB.XFBML.parse();
    };

    //load the JavaScript SDK
    (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'));
}

Also, make sure to use this with a server (public or localhost), don´t just open the html file in your Browser. You should also consider putting the Facebook stuff in a separate file, so you can use it in future projects. But first, make sure it works and make sure you understand what´s happening.

Keep in mind that you may need to use FB.XFBML.parse in componentDidUpdate too. You have to make sure the JS SDK is loaded already for that. componentDidMount will only get called once, and if you go to another route and back to this component, it will be cached and you need to parse Social Plugins again.

More information about the JS SDK: http://www.devils-heaven.com/facebook-javascript-sdk-login/

You can get rid of the linting error by using /*global FB*/ at the head of your files, or (much better) by defining FB in the .eslintrc file (if using ESLint):

"globals": {
    "FB": true
}
andyrandy
  • 72,880
  • 8
  • 113
  • 130
  • if you downvote an answer, please explain the reason. i am happy to improve my answer there is something wrong. – andyrandy Jul 22 '16 at 07:38
  • For me, the accepted answer from here https://stackoverflow.com/questions/40466492/how-to-fix-error-fb-is-not-defined-no-undef-on-create-react-app-project worked. Maybe will help someone else too. – Ionut Necula Jan 16 '18 at 18:30
  • thank you, i somehow missed the "linting" part, so i edited my answer. – andyrandy Jan 16 '18 at 20:23
  • i´ve also created a new answer in the other thread, because putting the comment in every single file is not a good solution: https://stackoverflow.com/questions/40466492/how-to-fix-error-fb-is-not-defined-no-undef-on-create-react-app-project/48289250#48289250 – andyrandy Jan 16 '18 at 20:25
0

You are trying to execute

  FB.init();
  FB.XFBML.parse();

When the SDK is not even loaded, so, of course, you will get the undefined reference error.

You are missing the callback

  window.fbAsyncInit = function() {
      // Example: Standard initialization code:
      FB.init({
        appId      : '{your-app-id}',
        status     : true,
        xfbml      : true,
        version    : 'v2.4' // or v2.0, v2.1, v2.2, v2.3
      });
      FB.XFBML.parse();
  };

This code loads the SDK asynchronously so it does not block loading other elements of your page. This is particularly important to ensure fast page loads for users and SEO robots.

The URLs in the above code are protocol relative. This lets the browser to load the SDK over the same protocol (HTTP or HTTPS) as the containing page, which will prevent "Insecure Content" warnings.

The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.

Furthermore, you should set the callback before loading the SDK

window.fbAsyncInit = function() {
    // Example: Standard initialization code:
    FB.init({
      appId      : '{your-app-id}',
      status     : true,
      xfbml      : true,
      version    : 'v2.4' // or v2.0, v2.1, v2.2, v2.3
    });
    FB.XFBML.parse();
};

(function (d, s, id) {
const fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
  return;
}
const js = d.createElement(s); js.id = id;
js.async = true;
js.src = '//connect.facebook.net/fr_CA/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Jose Paredes
  • 3,882
  • 3
  • 26
  • 50
  • thanks!, i've added this. But i'm still getting the lint error. Also i've added this to my example above – frosty Jun 16 '16 at 09:09
  • I have edited my answer, by default FB.init requires parameters as I have updated my answer – Jose Paredes Jun 16 '16 at 09:22
  • Be sure that you are not using the FB object out of the scope fbAsyncInit – Jose Paredes Jun 16 '16 at 09:31
  • I'm still getting the lint error FB is not define. I think you on the money with the out of scope comment. But i can't get my head around how to define FB in react – frosty Jun 16 '16 at 10:30
  • You don't define the FB object the bootstrap does that, are you sure you are not using FB object out of ´componentDidMount´ ? – Jose Paredes Jun 16 '16 at 10:31
0

If you want to add any social share buttons to your react pages then you can try out npm module react-share which is very easy compared to native APIs by FB, Twitter etc.

Sample react-share code snippet at https://samvikshana.weebly.com/blog/react-share-social-share-widgets

Pavan
  • 819
  • 6
  • 18