facebook
George Anderson
Frontend and backend development guru, lover of all things computer... and cats! Hopes to make your coder life a breeze by sharing some tips and tricks of the trade.
Posted on Sep 26th 2019

In this article, we will use React Native to build a mobile application which we will authenticate with Facebook. React Native is a JavaScript framework for writing mobile applications for iOS and Android, based on the very popular React framework. We will be using CodeMix and Expo to help us develop the application. Source for this project can be accessed at this repository.

Getting Started: Configuring the Development Environment

For this tutorial, we will be using the Eclipse IDE with the CodeMix plugin installed.

If you’re looking for an IDE to take on development with frameworks like Angular, React, and Vue.js, or languages like Python and Rust, CodeMix has you covered. For Vue, install the Vue pack or the famed Vetur extension for Vue support. Codemix is compatible with all Eclipse-based IDEs and tools, such as MyEclipse, Spring Tools Suite, and JBoss Tools.

Setting Up

Expo is a toolchain built around React Native to help you quickly start an app. It provides a set of tools that simplify the development and testing of React Native apps.

Building mobile applications for iOS and Android normally requires installing and configuring XCode or Android Studio, but with Expo, these tools aren’t required. We just need to install the Expo CLI and the Expo client app on our iOS or Android devices.

To be able to authenticate with Facebook, we first need to create a Facebook app. Once created, we’ll build our React Native application, referencing the app just built.

Creating a Facebook App

First, go to https://developers.facebook.com/apps/ and sign up if you have not yet done so. Then, we need to follow the next steps to setup our Facebook App.


  1. Click on “Add a New App” and fill out the required information and submit. Make note of the app ID once it’s been created we will be needing that in this tutorial.
  2. Then we go to “Settings > Basic” and down below we click on the “Add Platform” Button and select the desired platform for our App, may it be iOS or Android.
  3. If we use an iOS mobile device, add host.exp.Exponent as an iOS Bundle ID.
  4. If we use an Android mobile device, add rRW++LUjmZZ+58EbN5DVhGAnkX4= as an Android key hash, this key is constant for all Expo users so it should be exactly the same. Your app’s settings should be set up and working now. 
Now that we are done with the Facebook part, let’s move on to the React application.

Create a New React Native Project

We will need to create a dummy project in Eclipse and use its Terminal to execute a couple of commands for the creation of our Project and its Expo files. Also, we need to install the Expo client app on your iOS or Android phone and connect to the same wireless network as your computer.


Expo CLI sets up a development environment on your local machine and you can be writing a React Native app within minutes. It can be installed using executing the following command in Terminal:

npm install -g expo-cli

To create a new React Native project execute the following command in terminal:

expo init AuthApp

The CLI will ask us to choose a type of template for our project, for this project we will choose the first option (Blank), and from there a name for our app that will be visible on Home Screen, we will input AuthApp as the project name.

Once the process is finished, we just need to go to the folder that we just created with Expo, for this we need to execute the command, cd AuthAppalso, we need to run the command npm install expo-facebook to install the last Expo module needed.

Now, we are ready to run Our app in our Smartphone Using Expo app, to do so, execute Npm start in the project terminal.

Now, you should get a browser tab with QR code like below, if the tab doesn’t open automatically, you can see on the terminal what is the localhost port being used, typically it is http://localhost:19000/.


Open the Expo app in your smartphone and scan the provided QR code. Your development environment is now successfully connected to your smartphone, it will now compile your app to your smartphone in real-time. it looks like as shown below:
React Native App
Let’s start coding by opening the App.js file and adding our imports:
import * as React from 'react';
import { Text, View, StyleSheet, Alert, TouchableOpacity, Image } from 'react-native';
import { Ionicons, FontAwesome } from "@expo/vector-icons";
import * as Facebook from 'expo-facebook';


Content assist while Developing React Native App

Next, let’s define the login method of our class. This will be the method that’s called when the login button is pressed, it uses thelogInWithReadPermissionsAsync Expo helper class of the Facebook method to prompt the user with a Facebook login screen.

Replace the first parameter, labeled APP_ID in the following code, with your App’s ID:


    export default class App extends React.Component {
    
      FBlogIn = async () => {
        try {
          const {
            type,
            token,
            expires,
            permissions,
            declinedPermissions
          } = await Facebook.logInWithReadPermissionsAsync("App_ID", {
            permissions: ["public_profile"]
          });
          
          if (type === "success") {
            // Get the user's name using Facebook's Graph API
        const response = await fetch(
          `https://graph.facebook.com/me?access_token=${token}`
        );
        Alert.alert("Logged in!", `Hi ${(await response.json()).name}!`);
      } else {
         alert(`Facebook Login Error: Cancelled`);
      }
    } catch ({ message }) {
      alert(`Facebook Login Error: ${message}`);
    }
  };

In the second half of the logIn method, if the request is successful, we’ll make a call to the Facebook Graph API using the token that was received from logging in to request the logged-in user’s information. Once the response resolves, we set the state accordingly, we’ll also need a simple render function and need to display a Login button for logging in, as well as Text elements that will display user information once the login has completed successfully.


render() {

  return (
    <View style={styles.container}>
    <Text style={{fontWeight: 'bold', color: '#fff', fontSize:30, justifyContent:'center', marginVertical:10}}>
          React Native devlopment using CodeMix
     </Text>
      <Image
        style={{width: 300, height: 300, alignContent: 'center'}}
        source={{uri: 'https://resources.cloud.genuitec.com/wp-content/uploads/2019/03/tutorials_livechat.gif'}}
      />

    <Text style={{fontWeight: 'bold', color: '#fff', fontSize:30, justifyContent:'center', marginVertical:10}}>
           Login With Facebook

    </Text>

        <TouchableOpacity
              style={{
                backgroundColor: "#3f5c9a",
                alignItems: "center",
                justifyContent: "center",
                width: "100%",
                height: 60,
                borderColor: "#3f5c9a",
                borderWidth: 1
              }}
              onPress={this.FBlogIn}
            >

              <FontAwesome name="facebook-f" size={20} color="white" />
            </TouchableOpacity>


    </View>
  );
}



Hyperlink Navigation

Finally, we’ll add styles to complete the layout, setting padding, margins, color, and font sizes:


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#000'
  }
});

Now, if we run the app, we’ll see our Login button, a login modal when the Login button is pressed, and the user’s information, which will be displayed once the user has successfully logged in:

Facebook login with React Native

And that should be it, we’ve finished building our React Native app!

Conclusion

In this article, we learned how to make a quick Mobile App using React Native and the Facebook API with the help of Expo. Remember that you can take a look at our repo if you need further assistance with this project.

If you’re not already on the latest CodeMix, download it now to take advantage of all it has to offer!

Have any questions or suggestions about this article or any of our services? Let us know your thoughts via Twitter or through the CodeMix forums. Happy Coding!