• Stars
    star
    439
  • Rank 99,247 (Top 2 %)
  • Language
    Java
  • License
    MIT License
  • Created about 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Facebook Audience SDK integration for React Native

react-native-fbads npm version

chat

Facebook Ads

Facebook Audience SDK integration for React Native, available on iOS and Android. Features native, interstitial and banner ads.

Table of Contents

Prerequisites

You must have Facebook developer account in order to start integrating your app with this library. If you don't have one sign up here.

Follow the instructions on react-native-fbsdk-next to integrate the Facebook SDK into your project.

Get a Placement ID

Follow Facebook's instructions to create placement IDs for your ads. In order to get test ads modify your placement ID as it shown here.

Add test devices and test users

Follow Facebook's instructions to add test devices and add test users.

Android

You can get AAID from the android device/emulator by going to Settings > Google > Ads.

iOS

You can get IDFA from the iOS device using a third party app from the App Store. For simulators IDFA can be obtained by running this command: xcrun simctl list 'devices' 'booted'.

Note: Simulator must be booted.

Installation

Add the package to your project using either yarn:

yarn add react-native-fbads

or npm:

npm install --save react-native-fbads

Linking

React Native >= 0.60

CLI autolink feature links the module while building the app.

Note: for iOS make sure to install Pods through CocoaPods by running this command in your project's root directory: cd ios && pod install

For React-Native < 0.60 Link the native dependencies:
$ react-native link react-native-fbads

Expo installation

This package cannot be used in the "Expo Go" app because it requires custom native code.

First install the package with yarn, npm, or expo install.

expo install react-native-fbsdk-next react-native-fbads

After installing this npm package, add the config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "plugins": [
      [
        "react-native-fbsdk-next",
        {
          "appID": "48127127xxxxxxxx",
          "clientToken": "c5078631e4065b60d7544a95xxxxxxxx",
          "displayName": "RN SDK Demo",
          "advertiserIDCollectionEnabled": false,
          "autoLogAppEventsEnabled": false,
          "isAutoInitEnabled": true,
          "iosUserTrackingPermission": "This identifier will be used to deliver personalized ads to you."
        }
      ],
      "react-native-fbads"
    ]
  }
}

Next, rebuild your app as described in the "Adding custom native code" guide.

Usage

Interstitial Ads

An Interstitial Ad is a an ad that covers the whole screen with media content. It has a dismiss button as well as the clickable area that takes user outside of your app.

Interstitial ads are displayed over your root view with a single, imperative call.

On android, you'll need to add the following to your AndroidManifest.xml:

<activity
  android:name="com.facebook.ads.InterstitialAdActivity"
  android:configChanges="keyboardHidden|orientation" />

Usage:

import { InterstitialAdManager } from 'react-native-fbads';

InterstitialAdManager.showAd(placementId)
  .then((didClick) => {})
  .catch((error) => {});

The showAd method returns a promise that will be resolves once the ad has been either dismissed or clicked by the user. The promise will reject if an error occurs before displaying the ad, such as a network error.

If you want to preload the ad and show it later you can use this instead:

import { InterstitialAdManager } from 'react-native-fbads';

InterstitialAdManager.preloadAd(placementId)
  .then((didClick) => {})
  .catch((error) => {});

// Will show it if already loaded, or wait for it to load and show it.
InterstitialAdManager.showPreloadedAd(placementId);

Native Ads

Native Ads allow you to create custom ad layouts that match your app. Before proceeding, please review Facebook's documentation on Native Ads to get a better understanding of the requirements Native Ads impose.

1. Create the ads manager

import { NativeAdsManager } from 'react-native-fbads';

const adsManager = new NativeAdsManager(placementId, numberOfAdsToRequest);

The constructor accepts two parameters:

  • placementId - which is an unique identifier describing your ad units,
  • numberOfAdsToRequest - which is a number of ads to request by ads manager at a time, defaults to 10.

2. Create your component

Your component will have access to the following properties, under the nativeAd prop:

  • advertiserName - The name of the Facebook Page or mobile app that represents the business running each ad.
  • headline - The headline that the advertiser entered when they created their ad. This is usually the ad's main title.
  • linkDescription - Additional information that the advertiser may have entered.
  • translation - The word 'ad', translated into the language based upon Facebook app language setting.
  • promotedTranslation - The word 'promoted', translated into the language based upon Facebook app language setting.
  • sponsoredTranslation - The word 'sponsored', translated into the language based upon Facebook app language setting.
  • bodyText - Ad body
  • callToActionText - Call to action phrase, e.g. - "Install Now"
  • socialContext - social context for the Ad, for example "Over half a million users"

In addition, you'll have access to the following components:

  • MediaView for displaying Media ads
  • AdIconView for displaying the ad's icon
  • AdChoicesView for displaying the Facebook AdChoices icon.
  • TriggerableView for wrapping Text so it will respond to user clicks.

Please ensure you've reviewed Facebook's instructions to get a better understanding of each of these components and how you should use them.

import {
  AdIconView,
  MediaView,
  AdChoicesView,
  TriggerableView,
} from 'react-native-fbads';
class AdComponent extends React.Component {
  render() {
    return (
      <View>
        <AdChoicesView style={{ position: 'absolute', left: 0, top: 0 }} />
        <AdIconView style={{ width: 50, height: 50 }} />
        <MediaView style={{ width: 160, height: 90 }} />
        <TriggerableView>
          <Text>{this.props.nativeAd.description}</Text>
        </TriggerableView>
      </View>
    );
  }
}

export default withNativeAd(AdComponent);

4. Displaying Facebook Ad Choices Icon

Facebook's guidelines require every native ad to include the Ad Choices view, which contains a small clickable icon. You can use the included AdChoicesView component and style it to your liking.

Example usage

import { AdChoicesView } from 'react-native-fbads';

<AdChoicesView style={{ position: 'absolute', left: 0, top: 0 }} />;

Props

prop default required description
style undefined false Standard Style prop
expandable false false (iOS only) makes the native AdChoices expandable
location topLeft false (iOS only) controls the location of the AdChoices icon

5. Showing the ad

Finally, wrap your component with the withNativeAd HOC and pass it the adsManager you've previously created.

class MyAd {
 ...
}
export const AdComponent = withNativeAd(MyAd);

class MainApp extends React.Component {
  render() {
    return (
      <View>
        <AdComponent adsManager={adsManager} />
      </View>
    );
  }
}

BannerView

BannerView is a component that allows you to display ads in a banner format (know as AdView).

Banners are available in 2 sizes:

  • standard (BANNER_HEIGHT_50)
  • large (BANNER_HEIGHT_90)
import { BannerView } from 'react-native-fbads';

function ViewWithBanner(props) {
  return (
    <View>
      <BannerView
        placementId="YOUR_BANNER_PLACEMENT_ID"
        type="standard"
        onPress={() => console.log('click')}
        onLoad={() => console.log('loaded')}
        onError={(err) => console.log('error', err)}
      />
    </View>
  );
}

API

NativeAdsManager

Provides a mechanism to fetch a set of ads and then use them within your application. The native ads manager supports giving out as many ads as needed by cloning over the set of ads it got back from the server which can be useful for feed scenarios. It's a wrapper for FBNativeAdsManager

disableAutoRefresh

By default the native ads manager will refresh its ads periodically. This does not mean that any ads which are shown in the application's UI will be refreshed but simply that requesting next native ads to render may return new ads at different times. This method disables that functionality.

adsManager.disableAutoRefresh();

setMediaCachePolicy

Sets the native ads manager caching policy. This controls which media from the native ads are cached before being displayed. The default is to not block on caching.

adsManager.setMediaCachePolicy('none' | 'icon' | 'image' | 'all');

Note: This method is a noop on Android

AdSettings

import { AdSettings } from 'react-native-fbads';

AdSettings contains global settings for all ad controls.

currentDeviceHash

Constant which contains current device's hash id.

addTestDevice

Registers given device to receive test ads. When running on a real device, call this method with the result of AdSettings.currentDeviceHash to get test ads. Do not call this method in production.

You should register test devices before displaying any ads or creating any ad managers.

AdSettings.addTestDevice('hash');

clearTestDevices

Clears all previously set test devices. If you want your ads to respect newly set config, you'll have to destroy and create an instance of AdsManager once again.

AdSettings.clearTestDevices();

setLogLevel

Sets current SDK log level.

AdSettings.setLogLevel(
  'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'
);

Note: This method is a noop on Android.

setIsChildDirected

Configures the ad control for treatment as child-directed.

AdSettings.setIsChildDirected(true | false);

setMediationService

If an ad provided service is mediating Audience Network in their sdk, it is required to set the name of the mediation service

AdSettings.setMediationService('foobar');

setUrlPrefix

Sets the url prefix to use when making ad requests.

AdSettings.setUrlPrefix('...');

Note: This method should never be used in production

getTrackingStatus

Gets the current Tracking API status. As of iOS 14, Apple requires apps to only enable tracking (advertiser ID collection) when the user has granted tracking permissions.

Requires iOS 14. On Android and iOS versions below 14, this will always return 'unavailable'.

const trackingStatus = await AdSettings.getTrackingStatus();
if (trackingStatus === 'authorized' || trackingStatus === 'unavailable') {
  AdSettings.setAdvertiserIDCollectionEnabled(true);
}

The tracking status can return one of the following values:

  • 'unavailable': The tracking API is not available on the current device. That's the case on Android devices and iPhones below iOS 14.
  • 'denied': The user has explicitly denied permission to track. You'd want to respect that and disable advertiser ID collection.
  • 'authorized': The user has granted permission to track. You can now enable advertiser ID collection.
  • 'restricted': The tracking permission alert cannot be shown, because the device is restricted. See ATTrackingManager.AuthorizationStatus.restricted for more information.
  • 'not-determined': The user has not been asked to grant tracking permissions yet. Call requestTrackingPermission().

requestTrackingPermission

Requests permission to track the user. Requires an NSUserTrackingUsageDescription key in your Info.plist. (See iOS 14 Tracking API)

Requires iOS 14. On Android and iOS versions below 14, this will always return 'unavailable'.

const trackingStatus = await AdSettings.requestTrackingPermission();
if (trackingStatus === 'authorized' || trackingStatus === 'unavailable') {
  AdSettings.setAdvertiserIDCollectionEnabled(true);
  AdSettings.setAdvertiserTrackingEnabled(true);
}

setAdvertiserTrackingEnabled

Enables or disables personalized ads tracking on iOS 14+. See Facebook docs on Advertising Tracking Enabled For Audience Network

Requires iOS 14. On Android and iOS versions below 14, this will always be no-op. Important: FB won't display adds unless this is set to true.

AdSettings.setAdvertiserTrackingEnabled(true);

setAdvertiserIDCollectionEnabled

Enables or disables automatic advertiser ID collection. Since the iOS 14 API was introduced, you might want to disable advertiser ID collection per default (in Info.plist), and only enable it once the user has granted tracking permissions.

AdSettings.setAdvertiserIDCollectionEnabled(true);

Running the example

In order to see ads you will have to create your own placementId and use it instead of the one provided in the examples. This is our internal set up that doesn't work for any developers outside of Callstack.io organisation. This is because of Facebook not showing test ads to outside collaborators in the development mode.

1. Install dependencies

$ npm install

2. Start packager

Because of the way example project is set up (custom packager arguments), you'll have to start it explicitly before any other command

$ cd ./example && npm start

3. Run it on iOS / Android

$ cd ./example && npm run ios
$ cd ./example && npm run android

Credits

Some of the API explanations were borrowed from Facebook SDK documentation.

More Repositories

1

react-native-paper

Material Design for React Native (Android & iOS)
TypeScript
12,811
star
2

linaria

Zero-runtime CSS in JS library
TypeScript
11,659
star
3

haul

Haul is a command line tool for developing React Native apps, powered by Webpack
TypeScript
3,643
star
4

react-native-testing-library

πŸ¦‰ Simple and complete React Native testing utilities that encourage good testing practices.
TypeScript
3,078
star
5

react-native-builder-bob

πŸ‘·β€β™‚οΈ Simple set of CLIs to scaffold and build React Native libraries for different targets
JavaScript
2,771
star
6

react-native-pager-view

React Native wrapper for the Android ViewPager and iOS UIPageViewController.
TypeScript
2,711
star
7

repack

A Webpack-based toolkit to build your React Native application with full support of Webpack ecosystem.
TypeScript
1,471
star
8

reassure

Performance testing companion for React and React Native
TypeScript
1,269
star
9

react-native-slider

React Native component exposing Slider from iOS and SeekBar from Android
TypeScript
1,189
star
10

react-native-ios-kit

The missing React Native UI Kit for iOS
JavaScript
521
star
11

react-theme-provider

A set of utilities that help you create your own React theming system in few easy steps
JavaScript
466
star
12

super-app-showcase

Monorepository template for super app development with React Native and Re.Pack
JavaScript
413
star
13

react-native-image-editor

A library providing an API for cropping images from the web and the local file system.
Kotlin
373
star
14

react-native-brownfield

Set of helpers to make your brownfield integration smooth and easy.
Kotlin
241
star
15

react-native-paper-login-template

The easiest way to start with your application.
TypeScript
239
star
16

react-native-opentok

React Native OpenTok
Objective-C
202
star
17

component-docs

πŸ“ Simple documentation for your React components
TypeScript
137
star
18

react-native-open-source-board

OSS board with triaged React Native issues.
125
star
19

async-storage

Cross platform storage for React, built on top of AsyncStorage
JavaScript
109
star
20

react-native-material-palette

Bringing Material Palette API to React Native
JavaScript
105
star
21

ts-regex-builder

Maintainable regular expressions for TypeScript and JavaScript.
TypeScript
83
star
22

react-native-multibundle

JavaScript
57
star
23

eslint-config-callstack

ESLint preset extending Flow, Prettier and Jest
JavaScript
52
star
24

repack-examples

Repository with examples for Re.Pack
Java
50
star
25

ai-meeting-transcription

AI Tool for meeting transcriptions
Jupyter Notebook
36
star
26

react-native-socket-mobile

React Native module for the Socket Mobile SDK.
JavaScript
35
star
27

web3-react-native-dapp-wagmi

TypeScript
30
star
28

fabric-library-with-custom-cpp-example

Add custom cpp state to your fabric library
Java
29
star
29

super-app-example

This repository presents a compact super-app example from Callstack's blog, illustrating the use of a monorepo structure together with Re.Pack and Module Federation.
Java
27
star
30

hapi-graphql-boilerplate

JavaScript
26
star
31

react-native-detox-example

Example integration of Detox and Jest
Objective-C
23
star
32

linaria-styled

Zero-runtime CSS in JS library for building React components
18
star
33

web3-cross-platform-dapp

TypeScript
17
star
34

parcel-plugin-linaria

Parcel plugin for Linaria (Experimental)
JavaScript
17
star
35

benz-ql

GraphQL server for the Mercedes APIs
JavaScript
16
star
36

generator-node-module

A Yeoman module to author Node libraries with Prettier, Jest, Flow and Babel.
JavaScript
16
star
37

react-native-snapshot-tests

An example of snapshot testing with React Native
Objective-C
16
star
38

delightful-ux-training-app

JavaScript
15
star
39

universal-react-app

JavaScript
12
star
40

workshop-navigation

Navigation in React Native workshop.
JavaScript
12
star
41

ai-cli

AI assistant in your terminal.
TypeScript
11
star
42

github-comment-bot

JavaScript
10
star
43

news-mini-app-showcase

JavaScript
9
star
44

ReactNativeNotes

Notes demo application showing the abilities of React Native for desktop connected with UWP development
TypeScript
9
star
45

talk-universal-react

JavaScript
8
star
46

ai-summarization

AI summarization tool
Jupyter Notebook
7
star
47

react-native-releases-script

Script to generate changelog for RN releases
7
star
48

web3-react-native-dapp-viem

TypeScript
6
star
49

callstack-hackathon-team-ferran

callstack-hackaton-team-ferran
JavaScript
5
star
50

callstack-hackathon-team-dratwa-wojtek

JavaScript
3
star
51

reassure-examples

Examples for Reassure setup with different frameworks.
JavaScript
3
star
52

web3-react-native-testing

Best practices for testing React Native web3 dapps
TypeScript
3
star
53

DMAIC-Performance-Workshop

Dedicated app for the DMAIC Performance Workshop
TypeScript
2
star
54

.github

Templates for all Callstack OSS projects
2
star
55

react-native-paper-codemod

JavaScript
2
star
56

web3-react-native-siwe

Sign-In With Ethereum (SIWE) implementation in React Native
TypeScript
2
star
57

AppleVisionBGFX

Usage of BGFX in visionOS
C++
2
star
58

sample-weather-app

JavaScript
1
star
59

callstack.github.io

Organisation Github Page
HTML
1
star
60

react-native-visionos-docs

Documentation website for react-native-visionos
JavaScript
1
star
61

workshop-universal-sunshine

Universal React Native & React app based on Sunshine: https://github.com/udacity/Sunshine-Version-2
1
star