React JS Setup

The React OneSignal package is a JavaScript module that can be used to easily include OneSignal code in a website or app that uses React for its front-end codebase.

Requirements

If you have not done so already, you may benefit from following our Web Push Quickstart first.

πŸ“˜

Migration Guide

Version 3.0 was recently released. Read the Migration Guide here if you're coming from a version 2 release of the SDK.

Install

Yarn

yarn add react-onesignal

npm

npm install --save react-onesignal

Usage

Initialize OneSignal with your appId via the options parameter:

import OneSignal from 'react-onesignal';

OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });

The init function returns a promise that resolves when OneSignal is loaded.

//Example1
await OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });
// do other stuff

//Example2
const [initialized, setInitialized] = useState(false);
OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' }).then(() => {
  setInitialized(true);
  OneSignal.Slidedown.promptPush();
  // do other stuff
})

Local host example

When running locally, you can explicitly reference that you are connecting via an HTTP protocol. When configuring your integration in OneSignal, you will also need to set your domain to your local host and turn on local testing.

Create an async function that initializes OneSignal, and calls the showSlidedownPromp funciton.

import OneSignal from 'react-onesignal';

export default async function runOneSignal() {
  await OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', allowLocalhostAsSecureOrigin: true});
  OneSignal.Slidedown.promptPush();
}

Then you can call this function within your application to capture subscription preference.

import runOneSignal from './onesignal';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    runOneSignal();
  })

🚧

Calling useEffect in development mode may cause the SDK to Initialize Twice

When testing in a development environment, you may find that your OneSignal SDK is initialized twice and therefore produces a console error.

To resolve this, remove the <React.StrictMode> component from your root.

(Strict mode checks are run in development mode only; they do not impact the production build.)

Init Options

You can pass other options to the init function. Use these options to configure personalized prompt options, auto-resubscribe, and more.

Service Worker Params
You can customize the location and filenames of service worker assets. You are also able to specify the specific scope that your service worker should control. You can read more here.

In this distribution, you can specify the parameters via the following:

FieldDetails
serviceWorkerParamUse to specify the scope service worker has control of.
Recommendation: A non-root path that you will never host pages from.
- This prevents conflicts other Service Workers.
Example: { scope: "/onesignal" }
serviceWorkerPathThe path and file to your service worker file with OneSignal included.
Example: "/myPath/OneSignalSDKWorker.js"

Tip:
Visit https://{yoursite.com}/OneSignalSDKWorker.js in the address bar to make sure the files are being served successfully as javascript content. (Consider serviceWorkerParam if you customized it)

Service Worker File

If you haven't done so already, you will need to add the OneSignal Service Worker file to your site (learn more).

The OneSignal SDK file must be publicly accessible. You can put them in your top-level root or a subdirectory. However, if you are placing the file not on top-level root make sure to specify the path via the service worker params in the init options (see section above).

🚧

Compatibility with other Service Workers

If you have another Service Worker on your site make sure to change OneSignal's Service Worker Scope to prevent conflicts.


OneSignal API

Typescript

This package includes Typescript support.

interface IOneSignalOneSignal {
	Slidedown: IOneSignalSlidedown;
	Notifications: IOneSignalNotifications;
	Session: IOneSignalSession;
	User: IOneSignalUser;
	Debug: IOneSignalDebug;
	login(externalId: string, jwtToken?: string): Promise<void>;
	logout(): Promise<void>;
	init(options: IInitObject): Promise<void>;
	setConsentGiven(consent: boolean): Promise<void>;
	setConsentRequired(requiresConsent: boolean): Promise<void>;
}

OneSignal API

See the official OneSignal WebSDK reference for information on all available SDK functions.