# Quickstart: React Native

> Add the Herald React Native package to an app, identify a user, track an event, register for push and show content cards.

`@herald/react-native` is a thin wrapper over the native iOS and Android SDKs: every call goes to the native SDK, which validates, queues and sends it, and in-app messages are drawn by the native default views. This guide takes a React Native app from no SDK to a verified first event, a registered push token and a list of content cards. It takes about 30 minutes.

:::prereq
- React Native 0.88 or later with the New Architecture. The package is a TurboModule, built and tested with React Native 0.88; earlier versions aren't verified.
- iOS: deployment target iOS 16 or later (`platform :ios, '16.0'` in your `Podfile`), Xcode 16 or later. React Native adds the `herald-ios` Swift package to your Pods project for you.
- Android: `minSdkVersion` 26 or higher. A Firebase project with your Android app registered, and its `google-services.json`, for push.
- A Herald sending connection with an app key. In Herald, open **Settings > Sending**, open the connection and find the **Mobile SDK** card. If it has no key, click **Generate app key**. The card also shows your endpoint URL.
- A backend route that returns a user token for the signed-in user, unless identity verification is **Off**. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes).
:::

## 1. Install the package

The package is not on npm yet. It lives in `sdks/react-native` in the Herald repository, and installing it from git needs read access to that repository.

```sh
# pnpm installs a folder of a git repository directly
pnpm add "github:ender1311/herald#path:/sdks/react-native"

# npm or Yarn: pack it from a checkout, then install the tarball
git clone https://github.com/ender1311/herald.git
(cd herald/sdks/react-native && npm pack)
npm install ./herald/sdks/react-native/herald-react-native-0.6.0.tgz
```

Then install the iOS pods with `cd ios && pod install`. Android needs nothing more: the package depends on `herald-core` and `herald-ui` 0.6.0 from JitPack, a repository the React Native Gradle plugin already adds.

## 2. Configure the SDK

On iOS, call `Herald.configure` from JavaScript, once, before anything else. It also installs the native in-app message views.

On Android, call the native `Herald.configure` in `MainApplication.onCreate` instead. The Android SDK learns about the running activity from lifecycle callbacks it registers in `configure`, and a JavaScript call comes too late for the first launch: the session start and any in-app message would wait until the app next comes to the foreground, and push taps in `MainActivity` would be missed.

```tsx
// index.js or App.tsx
import { Platform } from 'react-native';
import { Herald } from '@herald/react-native';

if (Platform.OS === 'ios') {
  Herald.configure('YOUR_APP_KEY', 'https://YOUR_HERALD_HOST', { logLevel: 'debug' });
}
```

```kotlin
// android/app/src/main/java/.../MainApplication.kt
override fun onCreate() {
    super.onCreate()
    Herald.configure(this, "YOUR_APP_KEY", "https://YOUR_HERALD_HOST", HeraldOptions(logLevel = LogLevel.DEBUG))
    HeraldInAppPresenter.install()  // default in-app message views
    loadReactNative(this)
}
```

The options object takes the iOS names, in seconds: `deviceDataCollection`, `flushInterval`, `flushAt`, `foregroundSessionTimeout`, `backgroundSessionTimeout`, `inAppMinimumInterval`, `maxQueuedEventAge`, `logLevel`, `trackLifecycleEvents`, `trackDeepLinks`, `trackDeepLinkQuery`, `trackExternalPushes` and `crashReports` (iOS only). On Android, session timeouts are rounded up to whole minutes and `maxQueuedEventAge` to whole days. A second `configure` is ignored with a warning, as in the native SDKs.

## 3. Identify the user

After sign-in, call `identify` with your stable External ID, then `setUserToken` with the token your backend returns. Call them in that order: identifying a different user clears the previous token.

```tsx
Herald.identify(userId, { plan: 'free' });
Herald.setUserToken(userToken);
```

On sign-out, call `Herald.reset()`. `Herald.heraldId` is the person's User ID for a Support ID line.

## 4. Track an event

```tsx
Herald.track('workout_completed', { minutes: 32, type: 'strength' });
Herald.screen('Home');
Herald.trackPurchase('pro_monthly', 9.99, 'USD');
Herald.setAttributes({ favorite_sport: 'climbing' });
Herald.setEmail('ana@example.com');
```

Events are queued on the device and sent in batches. [Events and attributes](/docs/concepts/events-and-attributes) lists the rules each call must follow.

## 5. Register for push

`Herald.requestPushAuthorization()` shows the permission prompt (iOS, and Android 13 and later), records the answer and resolves with whether notifications are allowed. Push tokens and taps arrive in native code before JavaScript runs, so they are handled there.

iOS, in `AppDelegate.swift` (the app target can `import HeraldSDK`; the package links it):

```swift
import HeraldSDK

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    UNUserNotificationCenter.current().delegate = self
    return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Herald.shared.setPushToken(deviceToken)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    Herald.shared.handleNotificationResponse(response)
    completionHandler()
}
```

Android: add `herald-fcm` and the Google services plugin as in the [Android quickstart](/docs/overview/quickstart-android#1-add-the-modules), and pass notification taps on in `MainActivity`:

```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Herald.handleNotificationIntent(intent)
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    Herald.handleNotificationIntent(intent)
}
```

If another library already owns your push tokens (for example `@react-native-firebase/messaging`), pass each token on with `Herald.setPushToken(token)`: the APNs token as hex on iOS, the FCM token on Android. A push's deep link opens through the system, so React Native's `Linking` receives links to your own scheme. [iOS push setup](/docs/push-notifications/ios-setup) and [Android push setup](/docs/push-notifications/android-setup) cover the credentials.

## 6. Show content cards

The package gives you the card data; you draw the cards with your own components and log what the person sees and does.

```tsx
const [cards, setCards] = useState<ContentCard[]>([]);

useEffect(() => {
  Herald.getContentCards().then(setCards);
  const subscription = Herald.addContentCardsListener(setCards);
  return () => subscription.remove();
}, []);

// When a card is on screen, tapped or dismissed:
Herald.logImpression(card);
Herald.logClick(card);
Herald.logDismissal(card);
```

`Herald.refreshContentCards()` fetches cards and in-app messages now. Each card has the fields in the [iOS API](/docs/reference/ios-api#contentcard); timestamps are epoch milliseconds.

## 7. In-app messages

The native default views show in-app messages with no JavaScript. To hold a message back, set a handler. It gets the message's ID, type, priority, decision ID, expiry and content, and returns (or resolves with) `display`, `later` or `discard`, as the native delegate does:

```tsx
Herald.setInAppMessageHandler((message) => (isCheckingOut ? 'later' : 'display'));

// When the person is free again, offer the pending message (the handler is asked again):
Herald.showNext();
```

A handler that throws lets the message show. `Herald.setInAppMessageHandler(null)` goes back to showing every message as soon as it is eligible.

## What the package does not wrap

These work from the native side of your app with the native APIs ([iOS API](/docs/reference/ios-api), [Android API](/docs/reference/android-api)), but have no JavaScript call yet: Live Activities, push stories and geofences; `setLocation`, `setConsent` and `clearConsent`; `trackExternalPush`; `flush(timeout:)`; video logging; `deepLinkHandler`; custom in-app presenters and themes; and the debug preview calls. The package has no content card feed component.

## Verify it works

1. Run the app, sign in and log a workout. Send the app to the background: the SDK sends its queue as the app leaves the foreground.
2. With debug logging on, the native log shows the batch: in Xcode's console or Console.app filter by `Herald`; in Logcat filter by the tag `Herald`. `Sent 3 events` (or similar) confirms a batch was accepted.
3. In Herald, open **Audience > Search users** and look up the External ID. The profile shows the traits you passed to `identify`.
4. Have an agent send a content card to that user. Your card listener gets it at the next session start, or right away after `Herald.refreshContentCards()`.

## Troubleshooting

- **`TurboModuleRegistry.getEnforcing(...): 'HeraldReactNative' could not be found`.** The native part isn't in the build: run `pod install` again for iOS, rebuild the app (not only reload JavaScript), and check that the New Architecture is on.
- **Pod install fails on the deployment target.** Set `platform :ios, '16.0'` in your `Podfile` and the app target's deployment target to iOS 16.
- **Android manifest merger fails on `minSdkVersion`.** Set `minSdkVersion = 26` in `android/build.gradle`.
- **No in-app message on Android's first launch.** `configure` ran from JavaScript. Move it to `MainApplication.onCreate`.

The sample app in `sdks/react-native/example` in the repository shows every call above.

## Next

- [Users and identity](/docs/concepts/users-and-identity)
- [Content cards](/docs/content-cards/overview)
- [In-app messages](/docs/in-app-messages/overview)
