Because ‘Facebook Login’ is the new ‘Hello World Program’ for mobile developers ( react-native-fbsdk)

Sahil Sharma
5 min readJun 15, 2016

--

I haven’t really counted, but it seems almost as if every other Mobile app I come across nowadays, has a Facebook login feature. Lately, I’ve been exploring react-native a lot and find it to be pretty darn amazing in terms of the not-so-steep learning curve. Instead of writing a traditional ‘Hello World Tutorial for react-native’, I decided to write a guide on how to integrate Facebook Login in a react native app from scratch.

Let’s start with a basic, very simple blueprint/wireframe of the app we will try and build :

In the process of doing this, by the end of this post, you will learn the following concepts:

  • handling navigations in a react-native app
  • how to integrate a third party plugin in a react-native app (to implement facebook login)
  • making a graph api call ( to get information from facebook profile)

I won’t be going through each line of code here, but will try and highlight the gist of concepts stated above. For reference you can open/clone/fork the following git repo for the sample project:

Creating a react-native app and setting up the navigator

First make sure the environment is setup. Refer this document to setup the environment. Go to the command line, and create a new react native app using the simple command :

react-native init FacebookLoginProject

This will create the new project with the given name.

Let’s setup the navigator for our app. Open ‘index.ios.js’ and inside the main component’s render function, instead of the default view, we are returning the following code :

render() {
return (
<Navigator
initialRoute={{id: 'FirstScreen', name: 'Index'}}
renderScene={this.renderScene.bind(this)}
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
renderScene(route, navigator) {
var routeId = route.id;
if (routeId === 'FirstScreen') {
return (
<FacebookLoginScreen
navigator={navigator} />
);
}
if (routeId === 'Homepage') {
return (
<Homepage
navigator={navigator} />
);
}
}
  • in a Navigator component (from react-native module) a route is denoted by a simple javascript object with an id and name (you can add additional parameters as objects in the route).
  • initialRoute is an object denoting the route to be rendered first.
  • renderScene expects a function(renderScene in this example) to describe what route should what component.
  • configureScene is just a function which returns the configuration for the way we want to render the component in the route.

Integrating third party plugins (react-native-fbsdk)

We will be using the following open source wrapper to add facebook login functionality to our app:

After installing the plugin ( preferable using rnpm),you need to create an app on Facebook Dashboard to start using facebook apis. This process can be a little cumbersome if you are doing it for the first time. Simply, refer to these steps to create the app. Now, let’s create the FacebookLoginScreen component.

componentWillMount () {
console.log(AccessToken)
AccessToken.getCurrentAccessToken().then(
(data) => {
if(data) {
this.goToHomePage();
}
}
)
}
  • This particular code in the component checks if the user is already logged in. If he is logged in, we will get an access token, and in that case we call a function which calls a particular route for the homepage by simply replacing the route in the navigator as follows:
goToHomePage(accessToken) {
this.props.navigator.replace({id: 'Homepage'});
}
  • Now we render the login button as follows (LoginButton is available from react-native-fbsdk module installed above) :
render() {
return (
<View style={styles.container}>
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
this.goToHomePage();
}
)
}
}
}
/>
</View>
);
}
  • onLoginFinished expects a callback function which describes the post login behaviour of the app.In the current example we want to redirect the user to the homepage according to the wireframes.

Making a graph api call

Now let’s try and figure out the landing screen after login( Homepage component in our example).

constructor() {
super();
this.state = {
name : '',
pic : ''
}
}
  • This constructor just sets the initial state for the homepage component.
render() {
return (
<View style={styles.container}>
<Text style={styles.welcomeMsg}>Welcome</Text>
<Text style={styles.name}>{this.state.name}</Text>
<Image source={{uri:this.state.pic}} style={styles.image} />
<LoginButton
onLogoutFinished = {() => {
this.props.navigator.replace({id:'FirstScreen'})
}}
/>
</View>
);
}
  • The above render method of Homepage component returns a view containing two text nodes and an image. Note that every thing inside ‘{}’ symbols means it is javascript instead of jsx. (JSX is used to make the components look like html structure which we all are so used to. Read this to know more about JSX)
{this.state.name}
  • the above statement will simply replace the expression with the value of the javascript expression.
//Create response callback.
_responseInfoCallback
= (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
this.setState({name: result.name, pic: result.picture.data.url});
}
}

componentWillMount() {
// Create a graph request asking for user information with a callback to handle the response.
const infoRequest = new GraphRequest(
'/me?fields=name,picture',
null,
this._responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
}
  • The above block of code is responsible for making the graph api call. We use GraphRequest module to do so which is also provided by the ‘react-native-fbsdk’ like the LoginButton.
  • this.setState is the an important method (mistakes often happen here ) which will make sure that the components are re-rendered when the response comes back from the api.
  • ** Note that the following code WOULD NOT HAVE WORKED instead of this.setState
this.state = {name: result.name, pic:        result.picture.data.url}

The final app should now look something like following

Screenshots from the final app

Feel free to email me any questions regarding the project at sahilaug@gmail.com.

Happy coding.

Cheers !!!

--

--