user2953989
user2953989

Reputation: 2979

Errors when adding Facebook SDK to React website

I'm trying to add Facebooks SDK code right after my tag on the website built with React, but i'm getting errors. I think it's because my homepage is a .jsx template, but i'm not sure how else to include this code:

<script>
    window.fbAsyncInit = function () {
      FB.init({
        appId: '1813842465324998',
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v2.11'
      }); <- unexpected token, expected "}". SYNTAX ERROR

      // Broadcast an event when FB object is ready
      var fbInitEvent = new Event('FBObjectReady');
      document.dispatchEvent(fbInitEvent);
    };

    (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 = "https://connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  </script>

Upvotes: 0

Views: 117

Answers (1)

andyrandy
andyrandy

Reputation: 73984

JSX does not allow JavaScript tags. Instead, just use the whole JavaScript code in componentDidMount. Ideally, you would put it in a separate file for handling the JS SDK of Facebook.

It would be pointless to use a script tag anyway, after all you are using a JavaScript file already. Also, the render function could be called multiple times, but you should only load the JS SDK once.

Upvotes: 1

Related Questions