react-native-fbsdk-next
repository·master·Indexed 21 days ago
https://github.com/thebergamo/react-native-fbsdk-nextA 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.
What's inside react-native-fbsdk-next
- 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.
Check React Native compatibility
masterBefore installing, ensure your React Native version is compatible with the desired Facebook SDK version.
FB SDK react-native-fbsdk-nextversionRequired React Native Version >= 9.3.0+ > 4.3.0>=0.63.3*>= 9.0.0+ >= 3.0.1>= 0.60<= 8.0.1 react-native-fbsdk>= 1.0.0>= 0.60<= 8.0.1 react-native-fbsdk<= 0.10<= 0.59.x*Note: Versions after 4.2.0 only support React Native
>= 0.63.3to ensure compatibility with recent Xcode versions. Older versions are not supported.Use Limited Login on iOS
masterTo 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 theLoginButtonor inLoginManagerto enable this mode. The default is"enabled".AuthenticationTokenvsAccessToken: In Limited Login mode, anAccessTokenis unavailable. Instead, you must useAuthenticationToken.getAuthenticationTokenIOS().- Graph API Restriction: An
AuthenticationTokencannot be used to make requests to the Facebook Graph API. Attempting to do so will result in anOAuthException(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> ); } }Implement Aggregated Event Measurement (AEM) for iOS
masterAEM 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.logAEMEventto 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
AppEventsLoggercalls.```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:@Install react-native-fbsdk-next
masterInstall the library using Yarn or npm.
yarn add react-native-fbsdk-next # or npm install --save react-native-fbsdk-nextSetup react-native-fbsdk-next in Expo (Bare Workflow)
masterThis 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.
- Install the npm package.
- Add the
react-native-fbsdk-nextconfig plugin to thepluginsarray in yourapp.jsonorapp.config.js. - Rebuild your app using
npx expo prebuildand rebuild the native binaries.
{ "expo": { "plugins": ["react-native-fbsdk-next"] } }Mock react-native-fbsdk-next for Jest testing
masterTo 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.spyOnto 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 }))Run the react-native-fbsdk-next example project
masterTo run the provided example project, clone the main repository and execute the following commands in sequence from the root directory:
- Install dependencies:
yarn example:install - Start the bundler:
yarn example:start - Launch the application on your target platform:
yarn example:androidoryarn 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- Install dependencies:
Initialize the Facebook SDK
masterDue 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.mfile. This is recommended for optimal performance.Note: You must add the necessary imports for
AuthenticationServices,SafariServices, andFBSDKCoreKit.#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 }Perform Facebook Login
masterYou can implement Facebook login using either the pre-built
LoginButtoncomponent or theLoginManagerAPI for custom UI.Using LoginButton
The
LoginButtoncomponent provides a ready-to-use UI. UseonLoginFinishedto handle success, errors, or cancellations, andonLogoutFinishedfor 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> ); } }Setup Expo Bare Workflow for iOS
masterIf using Expo in Bare Workflow, your
AppDelegate.swiftextendsExpoAppDelegate. 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 } }Configure Facebook SDK for iOS (Swift)
masterFor React Native versions >= 0.77 using Swift, modify
/ios/PROJECT/AppDelegate.swift:- Add imports:
import FBSDKCoreKit import AppTrackingTransparency- 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) }- Add
openURLmethod (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 }