Facebook Login is used by thousands of android & iOS application because of its easy Login implementation. Facebook has more than 2.37 billion users around the globe at present time. In react native using the Facebook Login we can give the easy login facility to our application users because there is no need to register the application user and application users can directly login via their Facebook login details. The functionality is purely safe for everyone and there is no need to worry about your username and passwords security. The Facebook has given us our own Facebook Software development kit(SDK) which is kind of cool to use. So in this tutorial we would going to implement Facebook Login Integration Example Tutorial Explained for both Android & iOS react native applications. So let’s get started . In this tutorial we would show the logged in user Name and Profile picture.
Contents in this project React Native Facebook Login Integration Example Tutorial Explained for Android iOS:
1. The first step is to create a new react native project. If you don’t know how then read my this Getting started with react native tutorial. If you have already created the project then open your project folder in Command Prompt or Terminal like i did in below screenshot and execute below command to install the react-native-fbsdk NPM library.
1
|
npm install react–native–fbsdk —save
|
Screenshot of CMD:
2. Next step is to execute the link command to index the newly installed react-native-fbsdk library in your project. This command would refresh the complete project and make all the necessary changes in all the files.
1
|
react–native link react–native–fbsdk
|
3. After linking the library we have to make sure that its make all the necessary changes in all files. So Goto Your_React_Native_Project -> android -> app -> build.gradle file. Open the build.gradle file in notepad or notepad++ editor and put both below dependencies in dependencies block.
1
2
|
implementation project(‘:react-native-fbsdk’)
implementation ‘com.facebook.android:facebook-android-sdk:4.34.0’
|
Source code of my build.gradle file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
apply plugin: “com.android.application”
import com.android.build.OutputFile
project.ext.react = [
entryFile: “index.js”
]
apply from: “../../node_modules/react-native/react.gradle”
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId “com.project3”
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName “1.0”
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include “armeabi-v7a”, “x86”, “arm64-v8a”, “x86_64”
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile(“proguard-android.txt”), “proguard-rules.pro”
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = [“armeabi-v7a”:1, “x86”:2, “arm64-v8a”: 3, “x86_64”: 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation project(‘:react-native-fbsdk’)
implementation ‘com.facebook.android:facebook-android-sdk:4.34.0’
implementation fileTree(dir: “libs”, include: [“*.jar”])
implementation “com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}”
implementation “com.facebook.react:react-native:+” // From node_modules
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into ‘libs’
}
|
4. Open Your_React_Native_Project -> android -> settings.gradle . Put below lines if not present.
1
2
|
include ‘:react-native-fbsdk’
project(‘:react-native-fbsdk’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-fbsdk/android’)
|
5. Open Your_React_Native_Project -> android -> app -> src -> main -> java -> com -> Your_React_Native_Project -> MainApplication.java .You need to import the both below packages in your file.
1
2
3
4
|
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.FacebookSdk;
import com.facebook.CallbackManager;
import com.facebook.appevents.AppEventsLogger;
|
6. In your MainApplication class add a instance variable of type CallbackManager.
1
2
3
4
|
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {
return mCallbackManager;
}
|
7. After importing above packages we need to call the FBSDKPackage(mCallbackManager) in getPackages() block after putting a comma.
1
|
new FBSDKPackage(mCallbackManager)
|
Complete source code of my MainApplication.java class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
package com.project3;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
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;
import com.facebook.FacebookSdk;
import com.facebook.CallbackManager;
import com.facebook.appevents.AppEventsLogger;
public class MainApplication extends Application implements ReactApplication {
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {
return mCallbackManager;
}
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 FBSDKPackage(mCallbackManager)
);
}
@Override
protected String getJSMainModuleName() {
return “index”;
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
|
8. Goto Your_React_Native_Project -> android -> app -> src -> main -> java -> com -> Your_React_Native_Project -> MainActivity.java file. Import intent in it.
1
|
import android.content.Intent;
|
9. Now we need to override the onActivityResult() inbuilt method to provide our project to receive application events.
1
2
3
4
5
|
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
}
|
Complete Source code of MainActivity.java File:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package com.project3;
import com.facebook.react.ReactActivity;
import android.content.Intent;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return “project3”;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
}
}
|
Now your project is good to go. Next step is to register your project on Facebook Console.
10. Open Facebook Console website in your web browser.
11. Log-in with your own Facebook ID.
12. Click on Add a new App button.
13. We need to put our Application display name and contact email there & hit the Create App ID button.
14. Now on the Facebook Login Menu click on Setup.
15. Select Platform as Android.
16. There is no need to download the Facebook SDK. Now click on Next button.
17. On the Import the Facebook SDK page you don’t have to do anything. Simply click on Next button.
18. On the Tell us about your android project window, We need to put our Package name & default activity class name. You can find your app’s package name in Android Manifest file.
19. Now while pressing the SAVE button it will ask us again to use this package name so HIT the Use this package name button.
20. Next and most important step is to Enter the key hashes code here. You can read my Tutorial about getting key hash code in windows from here. After generating the Key hash code enter your code here and hit the Save button.
21. Next step is Enable Single sign in on your App.
22. Here you go now all of your Facebook console setup is complete. Now we need to Put our Facebook App ID in our react native project. On your Facebook console window you can fine the Facebook App ID so COPY it.
23. GoTo -> Your_React_Native_Project -> android -> app -> src -> main -> res -> values -> strings.xml file. Create a string named as facebook_app_id and put your own copied Facebook App Id here.
Source code of my strings.xml file:
1
2
3
4
|
<resources>
<string name=“app_name”>project3</string>
<string name=“facebook_app_id”>Put your Facebook APP ID Here</string>
</resources>
|
24. Goto Your_React_Native_Project -> android -> app -> src -> main -> AndroidManifest.xml file. We need to add a meta data with newly created Facebook app id string. Put below code in application block.
1
2
|
<meta–data android:name=“com.facebook.sdk.ApplicationId”
android:value=“@string/facebook_app_id”/>
|
Source code of my AndroidManifest.xml file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“com.project3”>
<uses–permission android:name=“android.permission.INTERNET” />
<application
android:name=“.MainApplication”
android:label=“@string/app_name”
android:icon=“@mipmap/ic_launcher”
android:roundIcon=“@mipmap/ic_launcher_round”
android:allowBackup=“false”
android:theme=“@style/AppTheme”>
<meta–data android:name=“com.facebook.sdk.ApplicationId”
android:value=“@string/facebook_app_id”/>
<activity
android:name=“.MainActivity”
android:label=“@string/app_name”
android:configChanges=“keyboard|keyboardHidden|orientation|screenSize”
android:windowSoftInputMode=“adjustResize”>
<intent–filter>
<action android:name=“android.intent.action.MAIN” />
<category android:name=“android.intent.category.LAUNCHER” />
</intent–filter>
</activity>
<activity android:name=“com.facebook.react.devsupport.DevSettingsActivity” />
</application>
</manifest>
|
Now all the configuration has completed and your project is ready to start the coding.
25. Open your project’s App.js file and import View, StyleSheet, Text, Alert and Image component.
1
2
3
|
import React, { Component } from ‘react’;
import { View, StyleSheet, Text, Alert, Image } from ‘react-native’;
|
26. Import LoginButton, AccessToken, GraphRequest and GraphRequestManager component from react-native-fbsdk library in your project.
1
|
import { LoginButton, AccessToken, GraphRequest, GraphRequestManager } from ‘react-native-fbsdk’;
|
27. Create constructor() function in your main class. In constructor create 3 States named as user_name, avatar_url and avatar_show.
1
2
3
4
5
6
7
8
9
|
constructor() {
super();
this.state = {
user_name: ”,
avatar_url: ”,
avatar_show: false
}
}
|
28. Create a function named as get_Response_Info() with error and result two parameters. In this function we would pop up the values from result object and store in states.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
get_Response_Info = (error, result) => {
if (error) {
Alert.alert(‘Error fetching data: ‘ + error.toString());
} else {
this.setState({ user_name: ‘Welcome’ + ‘ ‘ + result.name });
this.setState({ avatar_url: result.picture.data.url });
this.setState({ avatar_show: true })
console.log(result);
}
}
|
29. Create onLogout() function and set all the states values as null. We would call this function when user clicks on the Facebook Logout button.
1
2
3
4
5
|
onLogout = () => {
this.setState({ user_name: null, avatar_url: null, avatar_show: false });
}
|
30. Create Image, Text and Facebook Login button component in render’s return block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
render() {
return (
<View style={styles.container}>
{this.state.avatar_url ?
<Image
source={{ uri: this.state.avatar_url }}
style={styles.imageStyle} /> : null}
<Text style={styles.text}> {this.state.user_name} </Text>
<LoginButton
readPermissions={[‘public_profile’]}
onLoginFinished={(error, result) => {
if (error) {
console.log(error.message);
console.log(‘login has error: ‘ + result.error);
} else if (result.isCancelled) {
console.log(‘login is cancelled.’);
} else {
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString());
const processRequest = new GraphRequest(
‘/me?fields=name,picture.type(large)’,
null,
this.get_Response_Info
);
// Start the graph request.
new GraphRequestManager().addRequest(processRequest).start();
});
}
}}
onLogoutFinished={this.onLogout}
/>
</View>
);
}
|
31. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#fff’,
alignItems: ‘center’,
},
text: {
fontSize: 20,
color: ‘#000’,
textAlign: ‘center’,
padding: 20
},
imageStyle: {
width: 200,
height: 300,
resizeMode: ‘contain’
}
});
|
32. Complete source code for App.js file class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
import React, { Component } from ‘react’;
import { View, StyleSheet, Text, Alert, Image } from ‘react-native’;
import { LoginButton, AccessToken, GraphRequest, GraphRequestManager } from ‘react-native-fbsdk’;
export default class App extends Component {
constructor() {
super();
this.state = {
user_name: ”,
avatar_url: ”,
avatar_show: false
}
}
get_Response_Info = (error, result) => {
if (error) {
Alert.alert(‘Error fetching data: ‘ + error.toString());
} else {
this.setState({ user_name: ‘Welcome’ + ‘ ‘ + result.name });
this.setState({ avatar_url: result.picture.data.url });
this.setState({ avatar_show: true })
console.log(result);
}
}
onLogout = () => {
this.setState({ user_name: null, avatar_url: null, avatar_show: false });
}
render() {
return (
<View style={styles.container}>
{this.state.avatar_url ?
<Image
source={{ uri: this.state.avatar_url }}
style={styles.imageStyle} /> : null}
<Text style={styles.text}> {this.state.user_name} </Text>
<LoginButton
readPermissions={[‘public_profile’]}
onLoginFinished={(error, result) => {
if (error) {
console.log(error.message);
console.log(‘login has error: ‘ + result.error);
} else if (result.isCancelled) {
console.log(‘login is cancelled.’);
} else {
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString());
const processRequest = new GraphRequest(
‘/me?fields=name,picture.type(large)’,
null,
this.get_Response_Info
);
// Start the graph request.
new GraphRequestManager().addRequest(processRequest).start();
});
}
}}
onLogoutFinished={this.onLogout}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#fff’,
alignItems: ‘center’,
},
text: {
fontSize: 20,
color: ‘#000’,
textAlign: ‘center’,
padding: 20
},
imageStyle: {
width: 200,
height: 300,
resizeMode: ‘contain’
}
});
|
Screenshots: