Implement Facebook API login with reactjs

后端 未结 10 2004
广开言路
广开言路 2020-12-04 09:25

I\'m working on using Facebook\'s Javascript SDK for authentication. I\'ve been able to import the SDK properly and put a Like button on my page. But, the facebook login but

10条回答
  •  渐次进展
    2020-12-04 09:58

    This is the solution I used to get login callback. You can add this code for your Facebook login button in your render method:

    Login

    In your code, add these lines:

    componentDidMount: function() {
        // facebook signin  button render
        window.fbAsyncInit = function() {
          FB.init({
            appId      : 'replace with your app id here',
            cookie     : true,  // enable cookies to allow the server to access
            // the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v2.1' // use version 2.1
          });
    
          // login callback implementation goes inside the function() { ... } block
          FB.Event.subscribe('auth.statusChange', function(response) {
            // example implementation
            if (response.authResponse) {
              console.log('Welcome!  Fetching your information.... ');
              FB.api('/me', function(response) {
                console.log('Good to see you, ' + response.name + '.');
              });
            } else {
              console.log('User cancelled login or did not fully authorize.');
            }
          });
        }.bind(this);
    
        // Load the SDK asynchronously
        (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'));
      }
    }
    

    Calling FB.Event.subscribe('auth.statusChange', callback_function) during component initialization is important because that's basically your login callback. Checkout here for FB.Event documentation.

提交回复
热议问题