Code Monkey home page Code Monkey logo

react-native-fbsdk's Introduction

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 need to install the sdk with npm and configure native Android/iOS project in the react native project.

1. Create React Native project

First create a React Native project:

react-native init YourApp

2. Install JavaScript packages

Install rnpm:

npm install rnpm -g

Use rnpm to install and link the react-native-fbsdk package:

rnpm install react-native-fbsdk

3. Configure native projects

3.1 Android project

Assuming you have Android Studio installed, open the project with Android Studio. Go to MainActivity.java under app/src/main/java/com/<project name>/ to complete setup. Note that packages must be imported to use.

Add an instance variable of type CallbackManager in class.

import android.content.Intent;     // <--- import
import android.os.Bundle;

import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.reactnative.androidsdk.FBSDKPackage;

public class MainActivity extends ReactActivity {
    CallbackManager mCallbackManager;
    //...

Register sdk package in method getPackages().

@Override
protected List<ReactPackage> getPackages() {
    mCallbackManager = new CallbackManager.Factory().create();
    ReactPackage packages[] = new ReactPackage[]{
        new MainReactPackage(),
        new FBSDKPackage(mCallbackManager),
    };
    return Arrays.<ReactPackage>asList(packages);
}

Override onActivityResult().

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

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 follows the rest of the steps such as calling FacebookSdk.sdkInitialize and updating strings.xml and AndroidManifest.xml. Note that react-native project doesn't have the Application class, so you'll need to create an implementation of the Application class yourself.

3.2 iOS project

The react-native-fbsdk has been linked by rnpm, 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 in the Getting Started Guide for Facebook SDK for iOS.

3.3 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.
  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.

Usage

Login Button + Access Token

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

var Login = React.createClass({
  render: function() {
    return (
      <View>
        <LoginButton
          publishPermissions={["publish_actions"]}
          onLoginFinished={
            (error, result) => {
              if (error) {
                alert("login has error: " + result.error);
              } else if (result.isCancelled) {
                alert("login is cancelled.");
              } else {
                AccessToken.getCurrentAccessToken().then(
                  (data) => {
                    alert(data.accessToken.toString())
                  }
                )
              }
            }
          }
          onLogoutFinished={() => alert("logout.")}/>
      </View>
    );
  }
});

Requesting additional permissions with Login Manager

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

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

// ...

// Attempt a login using the Facebook login dialog asking for default permissions.
LoginManager.logInWithReadPermissions(['public_profile']).then(
  function(result) {
    if (result.isCancelled) {
      alert('Login cancelled');
    } else {
      alert('Login success with permissions: '
        +result.grantedPermissions.toString());
    }
  },
  function(error) {
    alert('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.

const FBSDK = require('react-native-fbsdk');
const {
  ShareDialog,
} = 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) {
        alert('Share cancelled');
      } else {
        alert('Share success with postId: '
          + result.postId);
      }
    },
    function(error) {
      alert('Share fail with error: ' + error);
    }
  );
}

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.

const FBSDK = require('react-native-fbsdk');
const {
  ShareApi,
} = 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) {
    alert('Share with ShareApi success.');
  },
  function(error) {
    alert('Share with ShareApi failed with error: ' + error);
  }
);

App events

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

// ...

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

Graph Requests

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

// ...

//Create response callback.
_responseInfoCallback(error: ?Object, result: ?Object) {
  if (error) {
    alert('Error fetching data: ' + error.toString());
  } else {
    alert('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();

License

See the LICENSE file.

Platform Policy

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

react-native-fbsdk's People

Contributors

dzhuowen avatar philikon avatar leggomyfroggo avatar grabbou avatar dabit3 avatar justinmakaila avatar philippkrone avatar maarekj avatar lalania avatar jmsaulnier avatar jdboivin avatar daxserver avatar robteix avatar plbrault avatar mingflifb avatar knowbody avatar kanerogers avatar john-griffin avatar devxoul avatar alfonsodev avatar alexeypodolian avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.