React OneSignal Integration

3.5.1 · active · verified Tue Apr 21

react-onesignal is a JavaScript/TypeScript module designed to streamline the integration of OneSignal's push notification, web push, and in-app messaging services into web applications. Currently at version 3.5.1, the library receives frequent patch and minor updates, indicating active development. While its name suggests a React-specific use, the library's documentation explicitly states it can be used in virtually any JavaScript front-end codebase. It acts as a wrapper around the OneSignal Web SDK, abstracting the direct script loading and providing a convenient, promise-based `init` method to configure the SDK. Key differentiators include its React-friendly API, managed script loading (with an option to override the script source), and strong TypeScript support, simplifying the development experience for push notification capabilities.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize OneSignal using the `init` function within a React component's `useEffect` hook, ensuring it's called only once. It shows how to await the initialization promise and conditionally render content based on the SDK's readiness.

import React, { useState, useEffect } from 'react';
import OneSignal from 'react-onesignal';

function PushNotificationHandler() {
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    const initializeOneSignal = async () => {
      try {
        await OneSignal.init({
          appId: process.env.ONE_SIGNAL_APP_ID ?? 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
          safari_web_id: process.env.ONE_SIGNAL_SAFARI_WEB_ID ?? '',
          notifyButton: {
            enable: true,
          },
          allowLocalhostAsSecureOrigin: true,
        });
        setInitialized(true);
        console.log('OneSignal initialized successfully');
        
        // You can prompt for push notifications here after initialization
        // OneSignal.Slidedown.promptPush();

      } catch (error) {
        console.error('Failed to initialize OneSignal:', error);
      }
    };

    if (!initialized) {
      initializeOneSignal();
    }
  }, [initialized]);

  if (!initialized) {
    return <div>Loading push notifications...</div>;
  }

  return (
    <div>
      <h1>Push Notifications Ready</h1>
      <p>OneSignal SDK is initialized and ready to use.</p>
      <button onClick={() => OneSignal.Slidedown.promptPush()}>Show Push Prompt</button>
    </div>
  );
}

export default PushNotificationHandler;

view raw JSON →