React Native OneSignal SDK

5.4.3 · active · verified Sun Apr 19

The React Native OneSignal SDK facilitates the integration of OneSignal's push notification, in-app messaging, email, and SMS services into iOS and Android applications built with React Native. The current stable version is 5.4.3. This library is actively maintained with frequent minor and patch releases, often addressing native SDK updates, bug fixes, and new features like the recent support for React Native's New Architecture (TurboModules) introduced in v5.4.0. Key differentiators include its comprehensive cross-platform support for various notification types and its user-centric APIs for managing user data across channels, distinguishing it from lower-level notification APIs provided by mobile OS platforms.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart code initializes the OneSignal SDK, sets an external user ID, and registers handlers for incoming notifications (foreground) and notification clicks. It also prompts for push notification permissions on iOS and Android 13+.

import React, { useEffect } from 'react';
import { View, Text, Alert, Platform } from 'react-native';
import OneSignal from 'react-native-onesignal';

const ONESIGNAL_APP_ID = process.env.ONESIGNAL_APP_ID ?? 'YOUR_ONESIGNAL_APP_ID';

const App = () => {
  useEffect(() => {
    // OneSignal Init Code
    OneSignal.setAppId(ONESIGNAL_APP_ID);

    // Method for setting the External User Id
    OneSignal.setExternalUserId('your-user-id-from-your-system');

    // Method for handling notifications received while app in foreground
    OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
      console.log("OneSignal: notification will show in foreground: ", notificationReceivedEvent);
      let notification = notificationReceivedEvent.get ;();
      Alert.alert("Notification Received", notification.body || '');
      notificationReceivedEvent.complete(notification);
    });

    // Method for handling notification clicks
    OneSignal.setNotificationOpenedHandler(notification => {
      console.log("OneSignal: notification opened: ", notification);
      Alert.alert("Notification Clicked", notification.notification.body || '');
    });

    // Prompt for push notifications (iOS) and Android 13+ permission
    if (Platform.OS === 'ios' || (Platform.OS === 'android' && parseFloat(Platform.Version) >= 33)) {
      OneSignal.promptForPushNotificationsWithProvisionalNotification();
    }

    return () => {
      // Clean up listeners if necessary
    };
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>OneSignal React Native Example</Text>
      <Text>Check console for OneSignal logs</Text>
    </View>
  );
};

export default App;

view raw JSON →