react-native-fbsdk-next

repository·master·Indexed 21 days ago

https://github.com/thebergamo/react-native-fbsdk-next

A community-driven wrapper for the Facebook iOS and Android SDKs that provides a JavaScript interface for Facebook integration in React Native applications. It supports features such as login and sharing, serving as an upgraded replacement for the original unsupported Facebook React Native module. Version 13.4.3.

Tokens
17.7K
Snippets
59
Records
68
Agent score
73%

What's inside react-native-fbsdk-next

  1. Overview of React Native FBSDK Next

    master
    React Native FBSDK Next is a community-maintained wrapper around the iOS and Android Facebook SDKs. It provides a unified JavaScript API to access Facebook features—ranging from login to sharing—without requiring developers to write native code. It is designed to maintain continuity for the original (now unsupported) Facebook React Native module, providing upgraded support and improvements for modern React Native applications.
  2. Check React Native compatibility

    master

    Before installing, ensure your React Native version is compatible with the desired Facebook SDK version.

    FB SDKreact-native-fbsdk-next versionRequired React Native Version
    >= 9.3.0+> 4.3.0>=0.63.3*
    >= 9.0.0+>= 3.0.1>= 0.60
    <= 8.0.1react-native-fbsdk >= 1.0.0>= 0.60
    <= 8.0.1react-native-fbsdk <= 0.10<= 0.59.x

    *Note: Versions after 4.2.0 only support React Native >= 0.63.3 to ensure compatibility with recent Xcode versions. Older versions are not supported.

  3. Use Limited Login on iOS

    master

    To comply with Apple's App Tracking Transparency (ATT), iOS users who opt out of tracking can use Limited Login.

    Key Concepts

    • loginTrackingIOS: Set this to "limited" on the LoginButton or in LoginManager to enable this mode. The default is "enabled".
    • AuthenticationToken vs AccessToken: In Limited Login mode, an AccessToken is unavailable. Instead, you must use AuthenticationToken.getAuthenticationTokenIOS().
    • Graph API Restriction: An AuthenticationToken cannot be used to make requests to the Facebook Graph API. Attempting to do so will result in an OAuthException (Code 190).
    • nonceIOS: You can optionally pass a custom non-empty string as a nonce for server-side validation.
    import React, { Component } from 'react';
    import { Platform, View } from 'react-native';
    import {
      AccessToken,
      AuthenticationToken,
      LoginButton,
    } from 'react-native-fbsdk-next';
    
    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 {
                  if (Platform.OS === "ios") {
                    AuthenticationToken.getAuthenticationTokenIOS().then((data) => {
                      console.log(data?.authenticationToken);
                    });
                  } else {
                    AccessToken.getCurrentAccessToken().then((data) => {
                      console.log(data?.accessToken.toString());
                    });
                  }
                }
              }}
              onLogoutFinished={() => console.log("logout.")}
              loginTrackingIOS="limited"
              nonceIOS="my_nonce"
            />
          </View>
        );
      }
    }
  4. Implement Aggregated Event Measurement (AEM) for iOS

    master

    AEM allows measuring app events from iOS 14.5+ users who have opted out of tracking. This requires both native and JavaScript setup.

    Step 1: Native Setup (AppDelegate/SceneDelegate)

    In your application:openURL:options: function, initialize the AEM Kit. The call sequence is important.

    Step 2: JavaScript Logging

    Use AEMReporterIOS.logAEMEvent to log events. This method is safe to call on all platforms; it will simply do nothing if the platform is not iOS.

    Note: Event names used in AEM must match the names used in your standard AppEventsLogger calls.

    ```objective-c
    // In AppDelegate.m or SceneDelegate.m
    #import <FBAEMKit/FBAEMKit-Swift.h>
    
    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
      [FBAEMReporter configureWithNetworker:nil appID:@
  5. Setup react-native-fbsdk-next in Expo (Bare Workflow)

    master

    This package requires custom native code and cannot be used in the 'Expo Go' app. To use it in an Expo project, you must use the Expo Bare Workflow.

    1. Install the npm package.
    2. Add the react-native-fbsdk-next config plugin to the plugins array in your app.json or app.config.js.
    3. Rebuild your app using npx expo prebuild and rebuild the native binaries.
    {
      "expo": {
        "plugins": ["react-native-fbsdk-next"]
      }
    }
  6. Mock react-native-fbsdk-next for Jest testing

    master

    To test components using this library, add the provided mock to your Jest setup file:

    jest.mock("react-native-fbsdk-next", () => require("react-native-fbsdk-next/jest/mocks").default);

    You can also use jest.spyOn to control the behavior of specific methods in your tests.

    import { LoginManager } from "react-native-fbsdk-next"
    
    // Mocking a specific implementation
    jest.spyOn(LoginManager, "logInWithPermissions").mockImplementation(() => Promise.resolve({ isCancelled: false }))
  7. Run the react-native-fbsdk-next example project

    master

    To run the provided example project, clone the main repository and execute the following commands in sequence from the root directory:

    1. Install dependencies: yarn example:install
    2. Start the bundler: yarn example:start
    3. Launch the application on your target platform: yarn example:android or yarn example:ios

    The example validates successful project integration for both Android and iOS, as well as basic Facebook SDK functionality like opening the login screen and the share dialog.

    yarn example:install
    yarn example:start
    yarn example:android
  8. Initialize the Facebook SDK

    master

    Due to Apple privacy requirements, the Facebook iOS SDK no longer supports auto-initialization. You must initialize the SDK manually using one of two methods:

    1. Platform-neutral (JavaScript)

    Use this method if you want to control initialization from your JS code (e.g., after a GDPR consent flow). This works on both iOS and Android.

    2. iOS Native Initialization

    To initialize the SDK as early as possible on iOS, add the following to your AppDelegate.m file. This is recommended for optimal performance.

    Note: You must add the necessary imports for AuthenticationServices, SafariServices, and FBSDKCoreKit.

    #import <AuthenticationServices/AuthenticationServices.h>
    #import <SafariServices/SafariServices.h>
    #import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      [FBSDKApplicationDelegate.sharedInstance initializeSDK];
      // your other stuff
    }
  9. Perform Facebook Login

    master

    You can implement Facebook login using either the pre-built LoginButton component or the LoginManager API for custom UI.

    Using LoginButton

    The LoginButton component provides a ready-to-use UI. Use onLoginFinished to handle success, errors, or cancellations, and onLogoutFinished for logout events.

    Using LoginManager

    For custom UI, use LoginManager.logInWithPermissions. This returns a Promise that resolves with the login result or rejects with an error.

    import React, { Component } from 'react';
    import { View } from 'react-native';
    import { AccessToken, LoginButton } from 'react-native-fbsdk-next';
    
    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>
        );
      }
    }
  10. Setup Expo Bare Workflow for iOS

    master

    If using Expo in Bare Workflow, your AppDelegate.swift extends ExpoAppDelegate. Follow this pattern:

    import Expo
    import React
    import FBSDKCoreKit
    import AppTrackingTransparency
    
    @UIApplicationMain
    public class AppDelegate: ExpoAppDelegate {
      
      public override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
      ) -> Bool {
        
        // Initialize Facebook SDK
        ApplicationDelegate.shared.application(
          application,
          didFinishLaunchingWithOptions: launchOptions
        )
        
        // Request tracking authorization
        if #available(iOS 14, *) {
          ATTrackingManager.requestTrackingAuthorization { _ in
            AppEvents.shared.activateApp()
          }
        } else {
          AppEvents.shared.activateApp()
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
      
      public override func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey: Any] = [:]
      ) -> Bool {
        let handledByFB = ApplicationDelegate.shared.application(
          app, open: url, options: options)
        let handledByRN = RCTLinkingManager.application(
          app, open: url, options: options)
        let handledBySuper = super.application(
          app, open: url, options: options)
        
        return handledByFB || handledByRN || handledBySuper
      }
    }
  11. Configure Facebook SDK for iOS (Swift)

    master

    For React Native versions >= 0.77 using Swift, modify /ios/PROJECT/AppDelegate.swift:

    1. Add imports:
    import FBSDKCoreKit
    import AppTrackingTransparency
    1. Initialize in didFinishLaunchingWithOptions:
    public override func application(
      _ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
      
      // Initialize Facebook SDK
      ApplicationDelegate.shared.application(
        application,
        didFinishLaunchingWithOptions: launchOptions
      )
      
      // Request App Tracking Transparency (iOS 14+)
      if #available(iOS 14, *) {
        ATTrackingManager.requestTrackingAuthorization { _ in
          AppEvents.shared.activateApp()
        }
      } else {
        AppEvents.shared.activateApp()
      }
      
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    1. Add openURL method (Required for Facebook SSO):
    public override func application(
      _ app: UIApplication,
      open url: URL,
      options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
      // Facebook SDK must be checked FIRST
      let handledByFB = ApplicationDelegate.shared.application(
        app, open: url, options: options)
      
      // Then React Native Linking
      let handledByRN = RCTLinkingManager.application(
        app, open: url, options: options)
      
      // Finally super
      let handledBySuper = super.application(
        app, open: url, options: options)
      
      return handledByFB || handledByRN || handledBySuper
    }
    public override func application(
      _ app: UIApplication,
      open url: URL,
      options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
      // IMPORTANT: Facebook SDK must be checked FIRST
      let handledByFB = ApplicationDelegate.shared.application(
        app, open: url, options: options)
      
      // Then React Native Linking
      let handledByRN = RCTLinkingManager.application(
        app, open: url, options: options)
      
      // Finally super
      let handledBySuper = super.application(
        app, open: url, options: options)
      
      return handledByFB || handledByRN || handledBySuper
    }