Branch Metrics React Native SDK

6.9.0 · active · verified Sun Apr 19

react-native-branch is the official React Native SDK for Branch Metrics, a comprehensive mobile linking and attribution platform. It enables developers to integrate deep linking, deferred deep linking, mobile attribution, and analytics into their React Native applications, supporting both iOS and Android platforms. The current stable version is 6.9.0, with frequent updates (typically monthly or bi-monthly) to align with native Branch SDK releases and to expose new methods for compliance and functionality. Key differentiators include its robust deep linking capabilities across platforms, detailed attribution analytics for marketing campaigns, and features like Universal Links and App Links for seamless user experiences. It abstracts much of the underlying native SDK complexity, providing a unified JavaScript interface.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Branch SDK, subscribe to deep link events, and create/log a Branch Universal Object and custom event.

import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, Alert, Linking } from 'react-native';
import branch, { BranchUniversalObject, BranchEvent } from 'react-native-branch';

const HomeScreen = () => {
  const [latestParams, setLatestParams] = useState(null);

  useEffect(() => {
    // Branch initialization and deep link subscription
    const unsubscribe = branch.subscribe(({ error, params, uri }) => {
      if (error) {
        console.error('Error from Branch: ' + error);
        return;
      }
      console.log('Branch Params:', params);
      console.log('Branch URI:', uri);
      setLatestParams(params);

      if (params['+non_branch_link']) {
        const nonBranchUrl = params['+non_branch_link'];
        Alert.alert('Non-Branch Link', `Opened non-Branch URL: ${nonBranchUrl}`);
        Linking.openURL(nonBranchUrl);
        return;
      }

      if (params['+clicked_branch_link']) {
        Alert.alert('Branch Link Opened', `Data: ${JSON.stringify(params, null, 2)}`);
        // Handle routing based on params (e.g., params.screen, params.productId)
      } else {
        Alert.alert('App Opened', 'No Branch link clicked or initial session.');
      }
    });

    // Example: Create a Branch Universal Object and generate a short URL
    const createAndShareLink = async () => {
      try {
        let buo = await branch.createBranchUniversalObject('content/12345', {
          locallyIndex: true,
          title: 'My Awesome Product',
          contentDescription: 'Check out this amazing product!',
          contentMetadata: {
            productId: '12345',
            itemCategory: 'electronics',
            customData: 'important_info',
          },
        });

        let linkProperties = {
          feature: 'share',
          channel: 'app_share',
          campaign: 'product_promo',
        };

        let controlParams = {
          $desktop_url: 'https://example.com/product/12345',
          $ios_url: 'https://apps.apple.com/app/id123456789',
          $android_url: 'https://play.google.com/store/apps/details?id=com.yourapp',
        };

        let { url } = await buo.generateShortUrl(linkProperties, controlParams);
        console.log('Generated Branch URL:', url);

        // Example: Log a custom event
        let event = new BranchEvent(BranchEvent.ViewItem, buo, {
          transaction_id: 'trans_abc123',
          currency: 'USD',
          revenue: 10.00,
        });
        event.logEvent();
        console.log('Logged custom event: ViewItem');

      } catch (err) {
        console.error('Error creating/logging Branch event or link:', err);
      }
    };

    createAndShareLink();

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Branch SDK Example</Text>
      {latestParams ? (
        <View>
          <Text style={styles.subtitle}>Latest Deep Link Params:</Text>
          <Text style={styles.params}>{JSON.stringify(latestParams, null, 2)}</Text>
        </View>
      ) : (
        <Text>Waiting for deep link or initial app open...</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#F5FCFF',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  subtitle: {
    fontSize: 18,
    fontWeight: '600',
    marginTop: 10,
    marginBottom: 5,
  },
  params: {
    fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
    fontSize: 12,
    backgroundColor: '#e0e0e0',
    padding: 10,
    borderRadius: 5,
  },
});

export default HomeScreen;

view raw JSON →