codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

React native app with facebook sdk login and firebase storage

--

In the following article I will show you how I successfully managed to integrate facebook login with facebook sdk and register the user into a firebase database.

TL:DR: you can find my example here.

My example is running on android, not sure if this works on iOS without some configuration. I will add in the near future a second article which will showcase the configuration for iOS too.

Firstly, we will initialize a new app so you won’t jump to the conclusion that I tricked you or something.

Assuming that you have react-native cli installed, if not, install it by typing:

npm install -g react-native-cli

We assume that you have Android Studio installed, if not, follow the steps here:

Now we are gonna init our project (see everything from scratch, instead of the setup for react native, that is annoying):

react-native init fbLoginWithFirebaseExample

Now we wait …

Dean waiting for his react native app to initialize

After react native finished the initialize, now you should start your server and run the app ( I prefer doing this on 2 separate tabs )

First is:

npm start

Second is:

react-native run-android

You should also see this: (I’m using my personal android phone for this: Android version is 6.0.1)

Now we got ourselves a react-native app. What I like to do next is to reorganize my files such as:

  • Create a new folder called : “src”
  • Move the whole file App.js in that folder
  • Modify index.js so that App will be imported from src: import App from ‘./src/App’;
  • We will create all the files inside the “src” folder and we will try to structure them by folders ( e.g. components, utils, config, etc … )

For now, we will close the node server and uninstall our app. This was mostly a test to see if all went well and to check if our app is running.

Now we need to install react-native-firebase and react-native-facebook-login

npm i react-native-firebase --save
npm i react-native-facebook-login --save

After they are installed we should link the packages

react-native link

Be careful: react-native link is dangerous if you already got an app and you want to add this feature, so I would recommend to follow the steps from their repositories in order to install the packages.

Before we will start our app again we need to make a new Firebase project.

From https://firebase.google.com/ proceed to console and click on “Add project”.

I will use the same name I gave to my app: fbLoginWithFirebaseExample.

Your first page should look like this:

Let’s add Firebase to our app.

Press “Add Firebase to your iOS app”

Fill it in with what you think but your bundle ID should look like : com.appName.ios

Press “REGISTER APP”

Download your “GoogleServie-info.plist” in your AppName/ios.

After that, just press “Continue” followed by “Finish”.

Now we are going to do the same thing for Android. Add another app and select “Android”.

I would advise you to use the same names as for iOS but for Android package name put “android” at the end.

Now we will use the same steps as for iOS, firstly registering our app and then download the google-services.json in our AppName/android/app folder.

After this, just continue and then finish.

Now we have both iOS and Android setup.

Let’s setup our authentication on Firebase, in order to do that, press the Authentication button in the left.

Press set-up sign in method and enable Facebook Login.

Note: you should provide and app ID and app secret from https://developers.facebook.com/

On facebook developers page you should have this enabled:

Proceed to settings in order to get both App ID and App Secret to your Facebook App and copy them into firebase.

Facebook Login should be enabled now:

Now we are done with the configurations.

Going back to our app: npm start and react-native run-android will start our app.

I modified App.js to render a button instead:

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button
} from 'react-native';
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<Button
onPress={() => console.log('dsa')}
title="Sign in with facebook"
color="#3c50e8"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});

Nothing fancy so far.

Now I usually create folders for all my files, I created a “lib” folder and an “auth” subfolder creating inside of it a file “index.js” with the following lines:

import { fbLoginPermissions } from '../../constants/index';
import firebase from '../../config/firebase';
import Auth from '../../config/auth';
export const handleFbLogin = () => (
Auth.Facebook.login(fbLoginPermissions)
.then((token) => {
firebase.auth()
.signInWithCredential(firebase.auth.FacebookAuthProvider.credential(token))
})
.catch((err) => this.onError && this.onError(err))
);

This will be our fbLogin function.

As you see, at top I imported 3 other constants, we are going to define them now.

In src make a new folder called “constants” and inside of it a file named “index”

export const fbLoginPermissions = ['email'];

This will be our fbPermissions constant. Personally, I like to keep them in folders such as constants for better storage of them and if you use this in multiple files you just edit this in case you will need an extra permission.

Now in src make another folder called “config”.

Here is where we will keep our authentication config and firebase config.

One file will be “auth”

import { FBLoginManager } from 'react-native-facebook-login';const Facebook = {
login: (permissions) => {
return new Promise((resolve, reject) => {
FBLoginManager.loginWithPermissions(permissions || ['email'], (error, data) => {
if (!error) {
resolve(data.credentials.token);
} else {
reject(error);
}
});
});
},
logout: () => {
return new Promise((resolve, reject) => {
FBLoginManager.logout((error, data) => {
if (!error) {
resolve(true);
} else {
reject(error);
}
});
});
}
}
const Auth = { Facebook };export default Auth;

The second file will be “firebase”

import RNFirebase from 'react-native-firebase'const configurationOptions = {
debug: true
}
const firebase = RNFirebase.initializeApp()export default firebase;

This should be it. Now you app tree should look like this

Note: this is my choice of organizing the project, if you don’t like it you can change it as you please.

I’m not a control freak as you see

Now let’s go back to our App.js and import our fbLogin function

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button
} from 'react-native';
import { handleFbLogin } from './lib/auth';export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<Button
onPress={handleFbLogin}
title="Sign in with facebook"
color="#3c50e8"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});

If you try to run your app with react-native run-android and get this error :

Don’t worry, I got you!

This error is because we forgot to add some things. We will add them now.

Also you will need to go to facebook developer page: https://developers.facebook.com/

In order to add the fb login feature.

When you will add fb login for android it will mention to you what files you need to edit, but I’m gonna show to you here too which are those files.

First is build.gradle from android/ ( Not from app/ )

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
maven {
url "https://maven.google.com"
}
}
}

next build.gradle from app/

just add these depencies

dependencies {
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.android.gms:play-services-base:11.2.0"
compile "com.google.firebase:firebase-core:11.2.0"
compile "com.google.firebase:firebase-auth:11.2.0"
compile project(':react-native-facebook-login')
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:+" // From node_modules
}

And at the bottom add:

apply plugin: 'com.google.gms.google-services'

Next file would be: “MainApplication.java”, located in app/src/main/java/com/appName/MainApplication.java.

you will need to add your FirebasePackage and Auth Package

package com.fbloginwithfirebaseexample;import android.app.Application;import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage; //firebase package
import io.invertase.firebase.auth.RNFirebaseAuthPackage; // Firebase Auth
import com.magus.fblogin.FacebookLoginPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),// firebase package
new RNFirebaseAuthPackage(), // firebase auth package
new FacebookLoginPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}

The most important file would be AndroidManifest.xml ( which I forgot to edit and my app crashed for 2 hours until I realized I forgot to edit this file )

Add the following lines before the “ </application>” tag

<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="Your App Name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>

Now the last file would be strings.xml

<resources>
<string name="app_name">fbLoginWithFirebaseExample</string>
<string name="facebook_app_id">your_app_id</string>
<string name="fb_login_protocol_scheme">your_app_id</string>
</resources>

After doing this we will run: react-native run-android again. The message should be the same as below.

If you get that Activity class error like I did don’t worry, that is an error shown because RN couldn’t start your app, but you will be able to find your app in your smatphone’s menu.

Now when we press the login button:

Success !!!

Also, now we are stored in the Firebase Database:

I hope that this tutorial helped adding the fb login sdk and firebase to your app.

Also, I put this example to a repo here.

Thank you for reading this.

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Robert Pop

Tech enthusiast, JavaScript addict, Mobile & Web developer. robipop.io

Responses (9)