Build React Native Fitness App #9 : [Android] Firebase Facebook Login

Build React Native Fitness App #9 : [Android] Firebase Facebook Login

in this chapter, we continue from the previous part that we did on iOS now we want to do on Android too. let brief first …

This tutorial is ninth chapter of series build fitness tracker this app use for track workouts, diets, or health activities and analyze data and display suggestion the ultimate goal is to create food and health recommendation using Machine learning we start with creating app that user wants to use and connect to google health and apple heath for gathering everything to create dataset that uses for train model later I start with ultimate goal. Still, we will start to create a react native app and set up screen navigation with React navigation. inspired by React native template from instamobile

your can view the previous chapter here

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch. Getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version.

A comprehensive step by step tutorial on building Android and iOS app from scratch using React Native

A comprehensive getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version. For more information about React Native definition, features, etc, you can find in their official documentation.

Shortcut to the steps:

  • Install React App Creator and Create A React Native App
  • Add Navigation Header and Home Screen
  • Load World Cup 2018 Data from API
  • Display List of World Cup Matchdays
  • Display World Cup 2018 Matchdays Details
  • Run the React Native World Cup 2018 App

In this React Native tutorial, we are creating an app that listing the World Cup 2018 matches using the free open public domain football data for the world cups in the JSON format.

The following tools, frameworks, and modules are required for this tutorial:

  • React Native
  • Node.js (NPM or Yarn)
  • Worldcup JSON data
  • Android Studio or SDK for Android
  • XCode for iOS
  • Terminal (OSX/Linux) or Command Line (Windows)
  • Text Editor or IDE (We are using Atom)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v8.11.1
npm -v
6.1.0
yarn -v
1.7.0

That's the Node and NPM or YARN version that we are using. In this tutorial, we will use Yarn commonly.

Install React App Creator and Create A React Native App

The Create React Native App is a tool for creating a React Native App. To install it, type this command in your App projects folder.

sudo npm install -g create-react-native-app

Then create a React Native App using this command.

create-react-native-app reactWorldCupApp

That command will create a React Native app then install all required modules. The app or project folder will contain these folders and files.

Next, go to the newly created React App folder.

cd reactWorldCupApp

This React Native App is running via Expo app, before running on your Android or iOS device, make sure you have to install the Expo App to Android or Expo Client to iOS. Of course, that app is available in the App Store. So, we assume that you have installed the Expo App in your device then type this command to run the app.

npm start

or

yarn start

You will see this barcode and instruction in the terminal or command line.

To open the app in the Android device, open the Expo App first then tap on Scan QR Code button. Scan the barcode in the terminal or command line then you will see the React Native Android App like this after waiting for minutes the build process.

For iOS Device, press s from the keyboard to send React Native App URL to your Email or SMS. Enter your phone number or Email address (We use an email address) then press Enter. You will get this email to your mailbox.

Choose open in Expo URL then open in your browser, that will be redirected to Expo App. In Expo App welcome screen, shake your phone to open the React Native App. Now, you will see this screen in your iOS device.

This step for development purpose, we will show you how to build for production at the end of this article.

Add Navigation Header and Home Screen

Above generated React Native App just show blank app with plain text. Now, we will show you how to add the Navigation Header and Home Screen for your app. So, it will look like the Native App. In the terminal or command line type this command to install React Navigation (react-navigation) module.

yarn add react-navigation

Next, create a folder for components and React Native components files in the root of the app folder.

mkdir components
touch components/HomeScreen.js
touch components/DetailsScreen.js

Open and edit components/HomeScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Home',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

export default HomeScreen;

Open and edit components/DetailsScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class DetailsScreen extends Component {
  static navigationOptions = {
    title: 'Details',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button
          title="Go to Details... again"
          onPress={() => this.props.navigation.push('Details')}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

export default DetailsScreen;

Next, open and edit App.js then add replace all codes with this.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import HomeScreen from './components/HomeScreen';
import DetailsScreen from './components/DetailsScreen';

const RootStack = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
    navigationOptions: {
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

When the files are saved, the Expo app will refresh the React Native App automatically. Now, the app will look like this.

Load World Cup 2018 Data from API

To load World Cup 2018 data from API, open and edit components/HomeScreen.js then add constructor function before rendering function.

constructor(props){
  super(props);
  this.state ={ isLoading: true}
}

Add function for load API JSON data which the JSON response set to the dataSource.

componentDidMount(){
  return fetch('https://raw.githubusercontent.com/openfootball/world-cup.json/master/2018/worldcup.json')
    .then((response) => response.json())
    .then((responseJson) => {
      // console.log(responseJson);
      this.setState({
        isLoading: false,
        dataSource: responseJson.rounds,
      }, function(){

      });

    })
    .catch((error) =>{
      console.error(error);
    });
}

The response from API holds by dataSource variable that will use in the view in the next step.

Display List of World Cup Matchdays

We will use the List and ListItem component of React Native Elements (react-native-elements) module. First, install react-native-elements using this command.

yarn add react-native-elements

Open and edit again components/HomeScreen.js then replace all imports with these imports of React, Component (react), StyleSheet, ScrollView, ActivityIndicator, Text, View (react-native), List, and ListItem (react-native-elements).

import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, Text, View  } from 'react-native';
import { List, ListItem } from 'react-native-elements';

Next, replace all render function with this React Native rendered template which the ActivityIndicator load only if the state status is loading. The list that gets from the data source displaying to the ListItem after mapping the array of the data source.

render() {
  if(this.state.isLoading){
    return(
      <View style={styles.activity}>
        <ActivityIndicator/>
      </View>
    )
  }

  return(
    <ScrollView style={styles.container}>
      <List>
        {
          this.state.dataSource.map((item, i) => (
            <ListItem
              key={i}
              title={item.name}
              leftIcon={{name: 'soccer-ball-o', type: 'font-awesome'}}
              onPress={() => {
                this.props.navigation.navigate('Details', {
                  matches: `${JSON.stringify(item.matches)}`,
                });
              }}
            />
          ))
        }
      </List>
    </ScrollView>
  );
}

Add style const before the export code.

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingBottom: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
  activity: {
    flex: 1,
    padding: 20,
  }
})
Display World Cup 2018 Matchdays Details

We will display World Cup 2018 Matchdays Details in the DetailsScreen. Open and edit components/DetailsScreen.js then replace all imports with this.

import React, { Component } from 'react';
import { StyleSheet, ScrollView, View } from 'react-native';
import { List, ListItem, Text, Card } from 'react-native-elements';

Next, replace all render function with these lines codes.

render() {
  const { navigation } = this.props;
  const matches = JSON.parse(navigation.getParam('matches', 'No matches found'));
  console.log(matches);

  return (
    <ScrollView>
      <Card style={styles.container}>
        {
          matches.map((item, key) => (
            <View key={key} style={styles.subContainer}>
              if(item.group) {
                <View>
                  <Text h3>{item.group}</Text>
                </View>
              }
              <View>
                <Text h3>{item.team1.name} vs {item.team2.name}</Text>
              </View>
              <View>
                <Text h5>{item.date}</Text>
              </View>
              <View>
                <Text h4>{item.score1} - {item.score2}</Text>
              </View>
              if(item.goals1.length > 0) {
                item.goals1.map((item2, key2) => (
                  <View key={key2}>
                    <Text h4>{item2.name} ({item2.minute})</Text>
                  </View>
                ))
              }
              if(item.goals2.length > 0) {
                item.goals2.map((item3, key3) => (
                  <View key={key3}>
                    <Text h5>{item3.name} ({item3.minute})</Text>
                  </View>
                ))
              }
            </View>
          ))
        }
      </Card>
    </ScrollView>
  );
}

Add StyleSheet const before the export code.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20
  },
  subContainer: {
    flex: 1,
    paddingBottom: 20,
    borderBottomWidth: 2,
    borderBottomColor: '#CCCCCC',
  }
})
Run the React Native World Cup 2018 App

To run the application in Expo App, you can find in step 1 of this article. If there's no error found, you will see the result like this.


Next, to run or build as the Native App, type this command to install React Native CLI first.

sudo npm install -g react-native-cli

Next, eject the project from the Create React Native App by type this command.

npm run eject

You will get questions like below, make it the same with the one that we choose.

? How would you like to eject from create-react-native-app? React Native: I'd like a regular React Native project.
We have a couple of questions to ask you about how you'd like to name your app:
? What should your app appear as on a user's home screen? React World Cup
? What should your Android Studio and Xcode projects be called? ReactWorldCupApp

Next, to run the Native iOS or Android App in the Simulator, type this command.

react-native run-ios
react-native run-android

That it's for now. Any suggestions are open for next React Native tutorial. You can find the full working source code in our GitHub.

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web. Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web. The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

Learn to use React Native for Web - Build a Workout App for iOS, Android, and Web

Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web. The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

💻 Code: https://github.com/benawad/react-native-web-series

⭐️ Contents ⭐️
⌨️ (0:00:00) Setting Up a React Native Web Project
⌨️ (0:09:04) Setting Up React Native Hooks
⌨️ (0:15:03) Setting Up a React Native Web Monorepo
⌨️ (0:28:24) Configuring React Native for Yarn Workspaces
⌨️ (0:39:58) How to use Mobx with React Hooks
⌨️ (0:49:15) Navigation in React Native Web
⌨️ (1:03:28) Styling a Component in React Native Web
⌨️ (1:27:40) Mobx Root Store
⌨️ (1:45:20) Workout Timer with Mobx
⌨️ (2:11:20) React Router with React Native Web
⌨️ (2:22:45) How to Persist Mobx Stores
⌨️ (2:30:47) Storing and Displaying Workout History
⌨️ (2:54:33) React Router Params in React Native Web
⌨️ (3:17:30) Floating Action Button React Native Web
⌨️ (3:34:45) Deploy React Native Web to Netlify

React Native Tutorial: Facebook login using React Native FBSDK

React Native Tutorial: Facebook login using React Native FBSDK

In this React Native tutorial, we will show you how to implementing or integrating Facebook login using React Native FBSDK (react-native-fbsdk) library/module. React Native FBSDK is a wrapper around the iOS Facebook SDK and Android Facebook SDK, allowing for Facebook integration in React Native apps

A comprehensive step by step React Native tutorial on implementing Facebook Login using React Native FBSDK including the working example.
Every access to the Native components is provided by Javascript modules. We have focused on the FB login that is the standard of almost all authenticated Mobile apps.

Table of Contents:

  • Setup a Facebook App
  • Install React Native CLI and Create App
  • Install React Native FBSDK (react-native-fbsdk) Module
  • Implements Facebook Login, Logout, and Share
  • Run and Test React Native Facebook Login App

The flow of this React Native FB login is very simple. Just a page with a "Sign in with Facebook" button which after clicking the FB login and successful login it will return with the basic info of your Facebook account. The following tools, frameworks, and modules are required for this tutorial:

  1. React Native
  2. Node.js (NPM or Yarn)
  3. react-native-fbsdk module
  4. React Native Elements
  5. Facebook Developer Dashboard
  6. Android Studio or SDK for Android
  7. XCode for iOS
  8. Terminal (OSX/Linux) or Command Line (Windows)
  9. Text Editor or IDE (We are using VSCode)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check the existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v10.15.1
npm -v
6.11.2
yarn -v
1.10.1
Setup a Facebook App

This step is about to set up or create a Facebook App to get the App ID and secret. Also, set the bundle ID for native iOS and Google Play package names for native Android. To set up or create a Facebook App, go to the Facebook Developers Dashboard. Login with your Facebook developers' account or credentials.

Click the + Add a New App button. Enter the display name (we use MyIonicApp name) then click the Create App ID button. Make sure to use the valid name allowed by Facebook Developers.

After checking the captcha dialog and click submit button, now, you can see App ID and Secret, write it to your notepad.

Click the Facebook Login Set up button.

Choose iOS first then on the iOS wizard scroll down to the bottom to enter iOS bundle ID that will supply on the XCode later.

Select SDK: Cocoapods as a development environment before using Facebook Login for iOS then click the Next button.

Enter iOS bundle ID that will supply on config.xml later (we use "com.djamware.myreactnativeapp") then click save then click the Continue button.

Enabled the Single Sign-On feature then click Save and Next button a few times until the end of the iOS steps. Next, click on the Android tab then click Download Android SDK.

Click the Next button 2 times then fill the Android project package name (we use "com.djamware.myreactnativeapp") and default Android Activity Class name.

Click the save button and this setup will check to the Google Play for the existence of this package name. You can ignore the popup message if there's no package found in the Google Play. Click the Continue button.

As you see, we need to create a Key Hashes. To get the key hashes, especially in development build open the terminal or command line then type this command.

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Enter "android" as the Key Pass.

Enter keystore password:  android
K1IC8IKUNGj8tt2BHTpm11c7uRE=

Copy and paste the Key Hashes like above to the Key Hashes field of the Facebook Android Setup then click save and continue button.

Enabled Single Sign-On then click Next button a few times until the end of the Facebook Android setup.

Install React Native CLI and Create App

This time we will use React Native CLI to create a React Native app because the Firebase Cloud Messaging will use natively. To install it, type this command in your App projects folder.

sudo npm install -g react-native-cli

Then create a React Native App using this command from your project directory.

react-native init ReactNativeFacebook

Next, go to the newly created React App folder and run the React Native app to the simulator.

cd ReactNativeFacebook && react-native run-ios

When a new terminal window opened, go to the React Native project folder then run the Metro bundler server.

cd ~/Apps/ReactNativeFacebook && yarn start

Now, you will see this in the iOS simulator.

Next, we will change the iOS and Android package name or bundle ID to match the Firebase configuration files. For iOS, open the ios/ReactNativeFacebook.xcworkspace file using XCode.

Just change the Bundle Identifier (ours: com.djamware.myreactnativeapp) and it ready to use with the Facebook App. For Android a little tricky, first, change the source folders which previously android/app/src/main/java/com/reactnativefacebook become android/app/src/main/java/com/djamware/myreactnativeapp.

Next, open and edit android/app/src/main/java/com/djamware/myreactnativeapp/MainActivity.java then this package name.

package com.reactnativefacebook;

to

package com.djamware.myreactnativeapp;

Do the same way to android/app/src/main/java/com/djamware/myreactnativeapp/MainApplication.java. Next, open and edit android/app/src/main/AndroidManifest.xml then change this line.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.reactnativefacebook">

To

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.djamware.myreactnativeapp">

Next, open edit android/app/build.gradle then change the application ID to the new package.

android {
    ...
    defaultConfig {
        applicationId "com.djamware.myreactnativeapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    ...
}

Next, open and edit android/app/BUCK then change the android_build_config and android_resource package name.

android_build_config(
    name = "build_config",
    package = "com.djamware.myreactnativeapp",
)

android_resource(
    name = "res",
    package = "com.djamware.myreactnativeapp",
    res = "src/main/res",
)

Finally, run this command from the android folder to clean up the Gradle.

cd android
./gradlew clean
Install React Native FBSDK (react-native-fbsdk) Module

To install React Native FBSDK (react-native-fbsdk) module, type this command.

yarn add react-native-fbsdk

or

npm install --save react-native-fbsdk

Next, you need to link this module to the Native iOS and Android using this command.

react-native link react-native-fbsdk

Configure Facebook SDK iOS

To configure the Facebook SDK for iOS, go to the iOS folder then install Cocoapods.

cd ios
pod install

Next, open the ReactNativeFacebook.xcworkspace file using XCode then right-click the Info.plist and select Open As -> Source Code. Add these lines of XML snippets before the closing of element.

CFBundleURLTypes

  
    CFBundleURLSchemes
    
      fb{your-app-id}
    
  

FacebookAppID
{your-app-id}
FacebookDisplayName
{your-app-name}
LSApplicationQueriesSchemes

  fbapi
  fb-messenger-share-api
  fbauth2
  fbshareextension

Change {your-app-id} and {your-app-name} with the Facebook App ID and Name that showed up in the Facebook Developer App Dashboard that previously created. Next, we have to manually add a few Obj-C codes to make Facebook App integration works. Open and edit AppDelegate.m the file then add this import.

#import 

Add FBSDKApplicationDelegate before the return line.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"ReactNativeFacebook"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

Also, add this method below didFinishLaunchingWithOptions method.

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                openURL:url
                                                      sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                             annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                  ];
  // Add any custom logic here.
  return handled;
}

To send the Facebook App event to the Facebook App Dashboard analytics add this method.

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

Configure Facebook SDK Android

To configure Facebook SDK for Android, open and edit the main or root Build.gradle then add this mavenCentral() repository to buildscript { repositories {}}.

repositories {
    google()
    jcenter()
    mavenCentral()
}

Next, open and edit android/app/build.gradle then add this dependency inside dependencies {} body.

implementation 'com.facebook.android:facebook-android-sdk:[5,6)'

Next, build this Android app to make the Facebook SDK library installed by type this command inside the android folder.

./gradlew build

Next, to add Facebook App ID to Android app, open and edit android/app/res/values/strings.xml then add this value.

YOUR_FB_ID

Replace YOUR_FB_ID with your Facebook App ID. Next, open and edit android/app/manifests/AndroidManifest.xml then make sure this permission added.


Add Facebook Application ID to the application element.

<application
   android:name=".MainApplication"
   ...>
   ...
   
 
Implements Facebook Login, Logout, and Share

Now, we will implement a Facebook login, logout, and share. First, we need to add React Native Elements to use the nice component for the React Native app. Type this command to install it.

yarn add react-native-elements
yarn add react-native-vector-icons

or

npm i react-native-elements --save
npm i --save react-native-vector-icons

Then link the react-native-vector-icons with the Native iOS and Android app.

react-native link react-native-vector-icons

Next, to implement Facebook login, logout, and share, we will use just a single existing App.js. Open and edit that file then add or modify these imports of React Hooks useState, useEffect, required React Native components, required React Native FBSDK components, and required React Native Elements components.

import React, { useState, useEffect } from 'react';
import {
  Alert,
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  StatusBar,
  Text,
  TouchableHighlight
} from 'react-native';

import {
  Header,
  Colors,
} from 'react-native/Libraries/NewAppScreen';
import { LoginButton, AccessToken, ShareDialog, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import { Card, Image } from 'react-native-elements'

Change the generated App constant to this declaration.

const App = () => {
...
}

Declare the required variable using React Hooks useState in the top of App constant body.

const [profile, setProfile] = useState([]);
const [profileImage, setProfileImage] = useState();
const [isLoggedIn, setLoggedIn] = useState(false);

Declare a constant variable as the content for Facebook shares.

const SHARE_LINK_CONTENT = {
  contentType: 'link',
  contentUrl: 'https://www.facebook.com/',
};

Add a function to get Facebook public_profile that put the response to profile and profileImage variables using setProfile and setProfileImage useState.

getPublicProfile = async () => {
  const infoRequest = new GraphRequest(
    '/me?fields=id,name,picture',
    null,
    (error, result) => {
      if (error) {
        console.log('Error fetching data: ' + error.toString());
      } else {
        console.log(result);
        setProfile(result);
        setProfileImage(result.picture.data.url);
      }
    }
  );
  new GraphRequestManager().addRequest(infoRequest).start();
}

Add a function or method to share the link with dialog opened and using the content from the previously declared constant variable.

shareLinkWithDialog = async () => {
  const canShow = await ShareDialog.canShow(SHARE_LINK_CONTENT);
  if (canShow) {
    try {
      const {isCancelled, postId} = await ShareDialog.show(
        SHARE_LINK_CONTENT,
      );
      if (isCancelled) {
        Alert.alert('Share cancelled');
      } else {
        Alert.alert('Share success with postId: ' + postId);
      }
    } catch (error) {
      Alert.alert('Share fail with error: ' + error);
    }
  }
};

Modify the View to implement the UI of Facebook Login, Profile, Share, and Logout.

return (
    
      
      
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          
          
            <LoginButton
              onLoginFinished={
                (error, result) => {
                  if (error) {
                    console.log("login has error: " + result.error);
                  } else if (result.isCancelled) {
                    console.log("login is cancelled.");
                  } else {
                    setLoggedIn(true);
                    AccessToken.getCurrentAccessToken().then(
                      (data) => {
                        console.log(data.accessToken.toString());
                        this.getPublicProfile();
                      }
                    )
                  }
                }
              }
              onLogoutFinished={() => {
                console.log("logout.");
                setLoggedIn(false);
              }}/>
            { isLoggedIn && <Card
                title={profile.name}>
                <Image
                  source={{ uri: profileImage }}
                  style={{ width: 50, height: 50 }}
                />
                
                  Share link with ShareDialog
                
              
            }
          
        
      
    
  );
};
Run and Test React Native Facebook Login App

To run the whole React Native Facebook Login App, first, re-link again the React Native to React Native FBSDK.

react-native unlink react-native-fbsdk
react-native link react-native-fbsdk

Run the React Native app to the Android device using this command. Make sure the Android device connected using USB cable and USB Debugging is enabled so it can be detected using ADB command.

react-native run-android

The new terminal tab will open then run the Metro Bundler after going to the root of the project folder.

cd ~/Apps/ReactNativeFacebook && yarn start

For the iOS, we can open the ios/ReactNativeFacebook.xcworkspace from the XCode then use the valid provisioning profile signing then run the iOS app from there while the Metro Bundler runs from the terminal.

That it's, the React Native Facebook login app. You can find the full source from our GitHub.