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
ritmatter gave a good answer, but I'll show how I did this a little differently. I wanted to use Facebook's login button rather than my own to trigger the callback for checking login state. The login button might look like this:
<div class="fb-login-button" onlogin="checkLoginState" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>
The button has an onlogin attribute, which the jsx parser doesn't support. Using data-onlogin in the react fashion wasn't working, so I just added the button in componentDidMount:
componentWillMount: function () {
window['statusChangeCallback'] = this.statusChangeCallback;
window['checkLoginState'] = this.checkLoginState;
},
componentDidMount: function () {
var s = '<div class="fb-login-button" ' +
'data-scope="public_profile,email" data-size="large" ' +
'data-show-faces="false" data-auto-logout-link="true" ' +
'onlogin="checkLoginState"></div>';
var div = document.getElementById('social-login-button-facebook')
div.innerHTML = s;
},
componentWillUnmount: function () {
delete window['statusChangeCallback'];
delete window['checkLoginState'];
},
statusChangeCallback: function(response) {
console.log(response);
},
// Callback for Facebook login button
checkLoginState: function() {
console.log('checking login state...');
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
},
render: function() {
return (
<div id='social-login-button-facebook'>
</div>
);
}
All that's left to do is trigger the button upon mounting the component if you want to automatically call checkLoginState.
I was recently working on Facebook Login for one of my project, So after going though many Stackoverflow answers and blog posts. I wrote a minimilastic code using ES6 FatArrow Function Expression (excluding .bind(this)). Hope this code helps you.
https://gist.github.com/ronit-mukherjee/3e933509643a4ab4e80452bb05c1a073
/*global FB*/
import React, {
Component
} from 'react';
class FacebookLoginButton extends Component {
componentDidMount() {
(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'));
window.fbAsyncInit = () => {
FB.init({
appId: '9999999999999999', //Change with your Facebook app id
autoLogAppEvents: true,
xfbml: true,
version: 'v3.0'
});
FB.Event.subscribe('auth.statusChange', response => {
if (response.authResponse) {
this.checkLoginState();
} else {
console.log('[FacebookLoginButton] User cancelled login or did not fully authorize.');
}
});
};
}
checkLoginState() {
FB.getLoginStatus(function(response) {
this.statusChangeCallback(response);
}.bind(this));
}
login() {
FB.login(this.checkLoginState(), {
scope: 'email'
});
}
statusChangeCallback(response) {
if (response.status === 'connected') {
this.testAPI();
} else if (response.status === 'not_authorized') {
console.log("[FacebookLoginButton] Person is logged into Facebook but not your app");
} else {
console.log("[FacebookLoginButton] Person is not logged into Facebook");
}
}
testAPI() {
FB.api('/me', function(response) {
console.log('[FacebookLoginButton] Successful login for: ', response);
});
}
render() {
return ( <
button className = "btn btn-block btn-fb"
onClick = {
() => this.login()
} >
<
i className = "fa fa-facebook" / > Connect with Facebook <
/button>
)
}
}
export default FacebookLoginButton;
Try using this library: https://github.com/keppelen/react-facebook-login
Works quite straightforward:
import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';
const responseFacebook = (response) => {
console.log(response);
}
ReactDOM.render(
<FacebookLogin
appId="1088597931155576"
autoLoad={true}
callback={responseFacebook} />,
document.getElementById('demo')
);
This is by far the cleanest and simplest way I could think of if you want to use the button from FB instead of your own.
To use the button, it's as simple as this.
<FbLoginBtn
width="250"
dataScope="public_profile,email"
onSuccess={callback}
onFailure={optionalCallback}
afterLogin={optionalCallback}
/>
This component is completely self-contained, and highly compostable because it doesn't rely on any external dependency nor does it have any predefined behavior other than rendering the FB login button.
import React, { Component } from 'react';
class FbLoginBtn extends Component {
constructor(props) {
super(props);
// post login behavior should be defined at a higher level
this.onSuccess = this.props.onSuccess || (() => {});
this.onFailure = this.props.onFailure || (() => {});
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentDidMount() {
// This is the meat of the component
// create a script tag, load FB SDK
// then after script is loaded, set related behavior
// If you have other components that rely on the FB SDK
// I recommend extracting this into its own module
let self = this;
let scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = "http://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4&appId=xxxxx";
scriptTag.addEventListener('load', function (e) {
self.FB = window.FB;
// I don't like exposing the SDK to global scope
window.FB = null;
// This subscribe the callback when login status change
// Full list of events is here
// https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.9
self.FB.Event.subscribe('auth.statusChange', self.onStatusChange.bind(self));
});
document.body.appendChild(scriptTag);
}
onStatusChange(response) {
if (response.status === 'connected') {
const { accessToken } = response.authResponse;
// I have a afterLogin optional callback
// which takes care of ads landing, invitation or any other custom behavior
this.onSuccess(accessToken, this.props.afterLogin);
} else {
this.onFailure();
}
}
render() {
return (
<div
className="fb-login-button"
data-width={this.props.width}
data-max-rows="1"
data-size="large"
data-button-type="login_with"
data-show-faces="false"
data-auto-logout-link="true"
data-use-continue-as="false"
data-scope={this.props.dataScope}
>
</div>
);
}
}
export default FbLoginBtn;