Skip to content

A React Native wrapper around the Facebook SDKs for Android and iOS. Provides access to Facebook login, sharing, graph requests, app events etc.

License

Notifications You must be signed in to change notification settings

rohanrana/react-native-fbsdk

 
 

Repository files navigation

React Native FBSDK

React Native FBSDK is a wrapper around the iOS Facebook SDK and Android Facebook SDK, allowing for Facebook integration in React Native apps. Access to native components, from login to sharing, is provided entirely through documented JavaScript modules so you don't have to call a single native function directly.

Functionality is provided through one single npm package so you can use it for both platforms without downloading any extra packages. Follow this guide to use react-native-fbsdk in your React Native app. You can also visit https://developers.facebook.com/docs/react-native for tutorials and reference documentation.


Installation

You will need either npm or Yarn in order to install the SDK and configure the Android and iOS projects.

1. Create React Native project

First create a React Native project:

react-native init YourApp

2. Install JavaScript packages

Run yarn (or npm install, if using npm) inside your new YourApp directory:

cd YourApp
yarn

Then, install the react-native-fbsdk package:

yarn add react-native-fbsdk

Or, if using npm:

npm install react-native-fbsdk

Finally, link the SDK to configure the iOS and Android projects:

react-native link react-native-fbsdk

3. Configure projects

3.1 Android

Assuming you have Android Studio installed, open the project with Android Studio.

Go to MainApplication.java under app/src/main/java/com/<project name>/ to complete setup.

Register SDK package in method getPackages().

import com.facebook.reactnative.androidsdk.FBSDKPackage;

// ...

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()
      );
    }
};

Also you need to add in your settings.gradle:

include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')

Before you can run the project, follow the Getting Started Guide for Facebook Android SDK to set up a Facebook app. You can skip the build.gradle changes since that's taken care of by the rnpm link step above, but make sure you follow the rest of the steps such as updating strings.xml and AndroidManifest.xml.

3.2 iOS

The react-native-fbsdk has been linked by react-native link. The next step will be downloading and linking the native Facebook SDK for iOS.

Make sure you have the latest Xcode installed. Open the .xcodeproj in Xcode found in the ios subfolder from your project's root directory. Now, follow all the steps except the pod install (Step 2) in the Getting Started Guide for Facebook SDK for iOS. Along with FBSDKCoreKit.framework, don't forget to import FBSDKShareKit.framework and FBSDKLoginKit.framework into your Xcode project.

If you're using React Native's RCTLinkingManager

The AppDelegate.m file can only have one method for openUrl. If you're also using RCTLinkingManager to handle deep links, you should handle both results in your openUrl method.

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  if ([[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options]) {
    return YES;
  }

  if ([RCTLinkingManager application:app openURL:url options:options]) {
    return YES;
  }

  return NO;
}

Troubleshooting

  1. I cannot run the Android project.
  • Make sure you added the code snippet in step 3.1.
  • Make sure you set up a Facebook app and updated the AndroidManifest.xml and res/values/strings.xml with Facebook app settings.
  1. I get a build error stating that one of the Facebook SDK files was not found -- eg. FBSDKLoginKit/FBSDKLoginKit.h file not found.
  • Make sure that the Facebook SDK frameworks are installed in ~/Documents/FacebookSDK.
  • Make sure that FBSDK[Core, Login, Share]Kit.framework show up in the Link Binary with Libraries section of your build target's Build Phases.
  • Make sure that ~/Documents/FacebookSDK is in the Framework Search Path of your build target's Build Settings. You may have to select the All tab to see and search for the Framework Search Path.
  1. I get build errors like Warning: Native component for "RCTFBLikeView" does not exist:
  • Make sure that libRCTFBSDK.a shows up in the Link Binary with Libraries section of your build target's Build Phases.
  1. I get this build error: no type or protocol named UIApplicationOpenURLOptionsKey:
  • Your Xcode version is too old. Upgrade to Xcode 10.0+.
  1. null is not an object (evaluating 'LoginManager.logWithPermission') issue
  • You have to download the latest facebook sdk because this sdk is not working and will run into errors like above
  • Then paste it into ~/Documents/FacebookSDK

Usage

Login Button + Access Token

import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken } from 'react-native-fbsdk';

export default class Login extends Component {
  render() {
    return (
      <View>
        <LoginButton
          onLoginFinished={
            (error, result) => {
              if (error) {
                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())
                  }
                )
              }
            }
          }
          onLogoutFinished={() => console.log("logout.")}/>
      </View>
    );
  }
};

Requesting additional permissions with Login Manager

You can also use the Login Manager with custom UI to perform Login.

// ...

import { LoginManager } from "react-native-fbsdk";

// ...

// Attempt a login using the Facebook login dialog asking for default permissions.
LoginManager.logInWithPermissions(["public_profile"]).then(
  function(result) {
    if (result.isCancelled) {
      console.log("Login cancelled");
    } else {
      console.log(
        "Login success with permissions: " +
          result.grantedPermissions.toString()
      );
    }
  },
  function(error) {
    console.log("Login fail with error: " + error);
  }
);

Share dialogs

All of the dialogs included are used in a similar way, with differing content types. All content types are defined with Flow Type Annotation in js/models directory.

// ...

import { ShareDialog } from 'react-native-fbsdk';

// ...

// Build up a shareable link.
const shareLinkContent = {
  contentType: 'link',
  contentUrl: "https://facebook.com",
  contentDescription: 'Wow, check out this great site!',
};

// ...

// Share the link using the share dialog.
shareLinkWithShareDialog() {
  var tmp = this;
  ShareDialog.canShow(this.state.shareLinkContent).then(
    function(canShow) {
      if (canShow) {
        return ShareDialog.show(tmp.state.shareLinkContent);
      }
    }
  ).then(
    function(result) {
      if (result.isCancelled) {
        console.log('Share cancelled');
      } else {
        console.log('Share success with postId: '
          + result.postId);
      }
    },
    function(error) {
      console.log('Share fail with error: ' + error);
    }
  );
}

Share Photos

See SharePhotoContent and SharePhoto to refer other options.

const FBSDK = require('react-native-fbsdk');
const {
  ShareApi,
} = FBSDK;

const photoUri = 'file://' + '/path/of/photo.png'
const sharePhotoContent = {
  contentType = 'photo',
  photos: [{ imageUrl: photoUri }],
}

// ...

ShareDialog.show(tmp.state.sharePhotoContent);

Share Videos

See ShareVideoContent and ShareVideo to refer other options.

const FBSDK = require('react-native-fbsdk');
const {
  ShareApi,
} = FBSDK;

const videoUri = 'file://' + '/path/of/video.mp4'
const shareVideoContent = {
  contentType = 'video',
  video: { localUrl: videoUri },
}

// ...

ShareDialog.show(tmp.state.shareVideoContent);

Share API

Your app must have the publish_actions permission approved to share through the share API. You should prefer to use the Share Dialogs for an easier and more consistent experience.

// ...

import { ShareApi } from 'react-native-fbsdk';

// ...

// Build up a shareable link.
const shareLinkContent = {
  contentType: 'link',
  contentUrl: "https://facebook.com",
  contentDescription: 'Wow, check out this great site!',
};

// ...

// Share using the share API.
ShareApi.canShare(this.state.shareLinkContent).then(
  var tmp = this;
  function(canShare) {
    if (canShare) {
      return ShareApi.share(tmp.state.shareLinkContent, '/me', 'Some message.');
    }
  }
).then(
  function(result) {
    console.log('Share with ShareApi success.');
  },
  function(error) {
    console.log('Share with ShareApi failed with error: ' + error);
  }
);

App events

// ...

import { AppEventsLogger } from "react-native-fbsdk";

// ...

// Log a $15 purchase.
AppEventsLogger.logPurchase(15, "USD", { param: "value" });

Graph Requests

// ...

import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk';

// ...

//Create response callback.
_responseInfoCallback(error: ?Object, result: ?Object) {
  if (error) {
    console.log('Error fetching data: ' + error.toString());
  } else {
    console.log('Success fetching data: ' + result.toString());
  }
}

// Create a graph request asking for user information with a callback to handle the response.
const infoRequest = new GraphRequest(
  '/me',
  null,
  this._responseInfoCallback,
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();

Example app

  • Run yarn start in the repo root to start the packager for the example app

iOS

  • Run pod install in example/ios
  • Open example/ios/RNFBSDKExample.xcworkspace with xcode
  • Run the example app

Android

  • Start a simulator
  • Run ./gradlew installDebug in example/android

Join the React Native community

See the CONTRIBUTING file for how to help out.

License

See the LICENSE file.

Platform Policy

Developers looking to integrate with the Facebook Platform should familiarize themselves with the Facebook Platform Policy.

About

A React Native wrapper around the Facebook SDKs for Android and iOS. Provides access to Facebook login, sharing, graph requests, app events etc.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 37.1%
  • Objective-C 32.3%
  • JavaScript 28.4%
  • Ruby 1.3%
  • Python 0.9%