Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-branch

Package Overview
Dependencies
Maintainers
5
Versions
154
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-branch

Branch Metrics React Native SDK

  • 2.0.0-rc.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
51K
increased by93.59%
Maintainers
5
Weekly downloads
 
Created
Source

Branch Metrics React Native SDK Reference

build status npm version npm downloads MIT licensed

This is a repository of our open source React Native SDK. Huge shoutout to our friends at Dispatcher, Inc. for their help in compiling the initial version of this SDK. This SDK will help you handle iOS Universal Links, Android App Links and deferred deep links, do install attribution and much more!

2.0.0 beta

Version 2.0.0-rc.1 is now available in NPM with a simplified SDK integration process. See Release 2.0.0 for details.

branch.json It is now possible to control certain features of the Branch SDK using an optional configuration file in your project. See https://rnbranch.app.link/branch-json for details.

v1.1.0 The createBranchUniversalObject method is now async, so be sure to use await or handle the promise resolution, e.g.

let buo = await branch.createBranchUniversalObject(...)

or

branch.createBranchUniversalObject(...).then((buo) => {
  this.buo = buo
})

This method does not throw.

react-native v0.40 support is available in version 1.x. This is a non-backwards compatible update. If you need to stay on react-native <0.40 please fix your package.json version to react-native-branch@0.9. See Updating to 1.0.0 for details. Note that some build steps differ between 0.9 and 1.x. These are highlighted where applicable.

v0.8.0 If you have overridden onStop in MainActivity.java be sure not to invoke RNBranchModule.onStop().

Installation

For beta version 2.0.0 see Release 2.0.0. These instructions are for 0.9 and 1.x.

  1. npm install --save react-native-branch
  2. react-native link react-native-branch or link the project manually
  3. Add pod 'Branch' to your ios/Podfile (details)
  4. cd ios; pod install --repo-update
  5. Follow the setup instructions

Note that CocoaPods 1.x no longer automatically updates pod repositories automatically on pod install. To make sure you get the latest version of the Branch SDK, use --repo-update or run pod repo update before pod install.

If you are new to react-native or CocoaPods, read below for more details:

Carthage

If you would prefer to use Carthage, you can skip steps 3 & 4 above and instead add the following to your Cartfile:

github "BranchMetrics/ios-branch-deep-linking"

Then run:

carthage update

If you're unfamiliar with how to add a framework to your project with Carthage, you can learn more here. You will need to maually link the framework by adding it to the "Linked Frameworks and Libraries" section of your target settings, and copy it by adding it to the "Input Files" section of your carthage copy-frameworks build phase.

Next Steps

In order to get full Branch support you will need to setup your ios and android projects accordingly:

Please see the Branch SDK Integration Guide for complete setup instructions.

Additional Resources

Usage

import branch, {
  AddToCartEvent,
  AddToWishlistEvent,
  PurchasedEvent,
  PurchaseInitiatedEvent,
  RegisterViewEvent,
  ShareCompletedEvent,
  ShareInitiatedEvent
} from 'react-native-branch'

// Subscribe to incoming links (both Branch & non-Branch)
branch.subscribe(({ error, params }) => {
  if (params && !error) {
  	// grab deep link data and route appropriately.
  }
})

let lastParams = await branch.getLatestReferringParams() // params from last open
let installParams = await branch.getFirstReferringParams() // params from original install
branch.setIdentity('theUserId')
branch.userCompletedAction('Purchased Item', {item: 123})
branch.logout()

let branchUniversalObject = await branch.createBranchUniversalObject('canonicalIdentifier', {
  automaticallyListOnSpotlight: true,
  metadata: {prop1: 'test', prop2: 'abc'},
  title: 'Cool Content!',
  contentDescription: 'Cool Content Description'})
branchUniversalObject.userCompletedAction(RegisterViewEvent)
branchUniversalObject.userCompletedAction('Custom Action', { key: 'value' })

let shareOptions = { messageHeader: 'Check this out', messageBody: 'No really, check this out!' }
let linkProperties = { feature: 'share', channel: 'RNApp' }
let controlParams = { $desktop_url: 'http://example.com/home', $ios_url: 'http://example.com/ios' }
let {channel, completed, error} = await branchUniversalObject.showShareSheet(shareOptions, linkProperties, controlParams)
let {url} = await branchUniversalObject.generateShortUrl(linkProperties, controlParams)
let spotlightResult = await branchUniversalObject.listOnSpotlight()

// optional: release native resources right away when finished with this BUO.
branchUniversalObject.release()

let rewards = await branch.loadRewards()
let redeemResult = await branch.redeemRewards(amount, bucket)
let creditHistory = await branch.getCreditHistory()

Linking

subscribe(listener)

listener (function)
Adds a change listener. Listener takes 1 argument with the shape { params, error}. The listener will be called for all incoming links as well as some other events, like initialization. If error is null, the params will always be non-null. Non-Branch links will have a +non_branch_link parameter. Branch links will have standard parameters. There is also a deprecated uri parameter that will be removed in a future release. For Branch links, it has the same value as the ~referring_link parameter. For non-Branch links, it has the same value as the +non_branch_link parameter.

getLatestReferringParams(): Promise

Returns a promise that resolves to the most recent referring params. Because params come in asynchronously, in most cases it is better to use the subscribe method to receive the params as soon as they are available.

getFirstReferringParams(): Promise

Returns a promise to resolves with the first install referring params.

params object

The params object is returned by various linking methods including subscribe, getLatestReferringParams, and getFirstReferringParams. Params will contain any data associated with the Branch link that was clicked before the app session began.

Branch returns explicit parameters every time. Here is a list, and a description of what each represents.

  • ~ denotes analytics
  • + denotes information added by Branch
ParameterMeaning
~channelThe channel on which the link was shared, specified at link creation time
~featureThe feature, such as invite or share, specified at link creation time
~tagsAny tags, specified at link creation time
~campaignThe campaign the link is associated with, specified at link creation time
~stageThe stage, specified at link creation time
~creation_sourceWhere the link was created ('API', 'Dashboard', 'SDK', 'iOS SDK', 'Android SDK', or 'Web SDK')
~referring_linkThe referring link that drove the install/open, if present
~idAutomatically generated 18 digit ID number for the link that drove the install/open, if present
+match_guaranteedTrue or false as to whether the match was made with 100% accuracy
+referrerThe referrer for the link click, if a link was clicked
+phone_numberThe phone number of the user, if the user texted himself/herself the app
+is_first_sessionDenotes whether this is the first session (install) or any other session (open)
+clicked_branch_linkDenotes whether or not the user clicked a Branch link that triggered this session
+click_timestampEpoch timestamp of when the click occurred
+urlThe full URL of the link that drove the install/open, if present (e.g. bnc.lt/m/abcde12345)

See also Deep Link Routing on the Branch documentation site for more information.

Any additional data attached to the Branch link will be available unprefixed.

User Methods

setIdentity(userId)

Set an identifier for the current user.

logout(userId)

Logout the current user.

userCompletedAction(label, payload)

Register a user action with Branch.

Branch Universal Object

createBranchUniversalObject(canonicalIdentifier, universalObjectOptions): Promise

Create a branch universal object.
canonicalIdentifier the unique identifier for the content.
universalObjectOptions options for universal object as defined below.
Returns a promise. On resolution, the promise returns an object with methods generateShortUrl, registerView, listOnSpotlight, showShareSheet, userCompletedAction (v1.1.0) and release (v1.1.0). This method does not throw.

The following methods are available on the resulting branchUniversalObject:
- userCompletedAction(event, state = {}): null

Introduced in version 1.1.0

Report a user action for this Branch Universal Object instance. Create a Branch Universal Object on page load and call userCompletedAction(RegisterViewEvent).

event an event name string, either one of the standard events defined by the SDK (as defined below) or a custom event name.
state an optional object with string properties representing custom application state

Returns null.

- showShareSheet(shareOptions, linkProperties, controlParams): object

shareOptions as defined below
linkProperties as defined below
controlParams as defined below
Returns an object with { channel, completed, error }

- generateShortUrl(linkProperties, controlParams): object

linkProperties as defined below
controlParams as defined below
Returns an object with { url }

- registerView()

Register a view for this universal object. Deprecated: Use userCompletedAction(RegisterViewEvent) instead.

- listOnSpotlight()

List the universal object on Spotlight (iOS only). Note: The recommended way to list an item on Spotlight is to use the automaticallyListOnSpotlight property with createBranchUniversalObject and then call userCompletedAction(RegisterViewEvent), e.g.

import branch, { RegisterViewEvent } from 'react-native-branch'

let universalObject = await branch.createBranchUniversalObject('abc', {
  automaticallyListOnSpotlight: true,
  title: 'Item title',
  contentDescription: 'Item description',
  contentImageUrl: 'https://example.com/image.png'
})
universalObject.userCompletedAction(RegisterViewEvent)

The automaticallyListOnSpotlight property is ignored on Android.

- release()

Introduced in version 1.1.0

(Optional) Immediately release native resources used by this Branch Universal Object instance. Those resources will eventually be removed if they are unused for some time, but you can also call release() when a BUO is no longer used, e.g. in componentWillUnmount(). (See the example apps in this repo.)

Register User Actions On An Object

We've added a series of custom events that you'll want to start tracking for rich analytics and targeting. Here's a list below with a sample snippet that calls the register view event.

EventDescription
RegisterViewEventUser viewed the object
AddToWishlistEventUser added the object to their wishlist
AddToCartEventUser added object to cart
PurchaseInitiatedEventUser started to check out
PurchasedEventUser purchased the item
ShareInitiatedEventUser started to share the object
ShareCompletedEventUser completed a share
import branch, { RegisterViewEvent } from 'react-native-branch'
let universalObject = await branch.createUniversalObject('abc', {})
universalObject.userCompletedAction(RegisterViewEvent)

Note that registerView() is deprecated in favor of userCompletedAction(RegisterViewEvent).

universalObjectOptions object

An object of options for the branchUniversalObject.

KeyTYPEDESCRIPTION
automaticallyListOnSpotlightBoolList this item on Spotlight (iOS). Ignored on Android.
canonicalIdentifierStringThe object identifier
contentDescriptionStringObject Description
contentImageUrlStringThe Image URL
contentIndexingModeStringIndexing Mode 'private' or 'public'
currencyStringA 3-letter ISO currency code (used with price)
expirationDateStringA UTC expiration date, e.g. 2018-02-01T00:00:00
keywordsArrayAn array of keyword strings
metadataObjectCustom key/value
priceFloatA floating-point price (used with currency)
titleStringThe object title
typeStringMIME type for this content
linkProperties object

An object of link properties.

KEYTYPEMEANING
aliasstringSpecify a link alias in place of the standard encoded short URL (e.g., [branchsubdomain]/youralias or yourdomain.co/youralias). Link aliases are unique, immutable objects that cannot be deleted. Aliases on the legacy bnc.lt domain are incompatible with Universal Links and Spotlight
campaignstringUse this field to organize the links by actual campaign. For example, if you launched a new feature or product and want to run a campaign around that
channelstringUse channel to tag the route that your link reaches users. For example, tag links with ‘Facebook’ or ‘LinkedIn’ to help track clicks and installs through those paths separately
featurestringThis is the feature of your app that the link might be associated with. eg: if you had built a referral program, you would label links with the feature referral
stagestringUse this to categorize the progress or category of a user when the link was generated. For example, if you had an invite system accessible on level 1, level 3 and 5, you could differentiate links generated at each level with this parameter
tagsarrayThis is a free form entry with unlimited values. Use it to organize your link data with labels that don’t fit within the bounds of the above
controlParams object

Control parameters for the link. All Branch control parameters are supported. See here for a complete list. In particular, these control parameters determine where the link redirects.

KEYTYPEMEANING
$fallback_urlstringChange the redirect endpoint for all platforms - so you don’t have to enable it by platform
$desktop_urlstringChange the redirect endpoint on desktops
$android_urlstringChange the redirect endpoint for Android
$ios_urlstringChange the redirect endpoint for iOS
$ipad_urlstringChange the redirect endpoint for iPads
$fire_urlstringChange the redirect endpoint for Amazon Fire OS
$blackberry_urlstringChange the redirect endpoint for Blackberry OS
$windows_phone_urlstringChange the redirect endpoint for Windows OS
shareOptions object
KEYTYPEMEANING
messageHeaderstringThe header text
messageBodystringThe body text
emailSubjectstringThe subject of the email channel if selected

Referral Methods

loadRewards()

Load rewards.

redeemRewards(amount, bucket)

Redeem rewards. amount the amount to redeem
bucket (optional) the bucket to redeem from.

getCreditHistory(): array

Get the credit history as an array.

Keywords

FAQs

Package last updated on 17 Aug 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc