Skip to main content

React SDK (Front-End)

The React SDK is mainly used for displaying In-App Notifications and allowing users to see and change their Notification Preferences.

Setup

  1. Install the react package using one of the following package managers:
npm install @notificationapi/react --legacy-peer-deps
yarn add @notificationapi/react
pnpm add @notificationapi/react

If you experience a React version conflict during package installation, try adding --force or --legacy-peer-deps to the end of your install command.

  1. Import and use our provider in your top-level components/routers:
App.tsx
import { NotificationAPIProvider } from '@notificationapi/react';

<App>
<NotificationAPIProvider
clientId="abc123" // your clientId found on the dashboard
userId="abcd-1234" // logged in userId
// or use this instead
// user={{
// id: "abcd-1234", // logged in userId
// }}
playSoundOnNewNotification={true} // Allow the user to hear default sound on new notification
>

<!-- your protected routes -->

</NotificationAPIProvider>
</App>;

Customizing the default sound

Change the deafult notification sound to include your own:

ParameterTypeDescription
playSoundOnNewNotificationbooleanDetermines to enable / disable sound. Default is off
newNotificationSoundPathstringDetermines the path for the new notification sound.
<App>
<NotificationAPIProvider
userId="abcd-1234" // logged in userId
clientId="abc123" // your clientId found on the dashboard
playSoundOnNewNotification={true} // Allow the user to hear default sound on new notification
newNotificationSoundPath="https://path-to-your-sound.mp3"
>

<!-- your protected routes -->

</NotificationAPIProvider>
</App>;

Customizing the path to web push service worker

The service worker must be placed in the public folder.

By default we assume the service worker file is publicly associable at https://yourdomain.com/notificationapi-service-worker.js

If the default path is not suitable for your application, you can customize the path to the web push service worker.

For example, the web push service worker is placed at public/service folder and is accessible at https://yourdomain.com/service/notificationapi-service-worker.js

<App>
<NotificationAPIProvider
userId="abcd-1234" // logged in userId
clientId="abc123" // your clientId found on the dashboard
customServiceWorkerPath="/service/notificationapi-service-worker.js"
>

<!-- your protected routes -->

</NotificationAPIProvider>
</App>;

Customizing the web push opt in message

By default we automatically figure out if your user should see the web push opt in message or not. You can customizing it like the following:

<App>
<NotificationAPIProvider
userId="abcd-1234" // logged in userId
clientId="abc123" // your clientId found on the dashboard
webPushOptInMessage={false}
>

<!-- your protected routes -->

</NotificationAPIProvider>
</App>;

In-App Notification Components

Click this 👉
<NotificationPopup />

Our popup component opens up to display your inbox for in-app notifications. This gives users a small interface for accessing their notifications without taking up screen space. Especially useful for mobile apps.

All notifications are displayed here, and each notification comes with buttons to mark notifications as "seen" or "archived". Additionally, the top right of the inbox contains features for setting user preferences and marking all notifications as read directlyfrom the inbox. If a notification has redirect, interacting with it will send users to that link or page from within the component.

<NotificationLauncher />

The popup launcher adds a button to the corner of the page (similar to chat buttons), that remains in place on your application. This gives users access to their inbox from anywhere on a page, so they don't need to scroll up to an inbox, or visit a dedicated inbox page to read and interact with notifications.

Counter (Standalone)

This is the counter 👉

<NotificationCounter />

The counter element displays the number of unread notifications. Features:

  • Can count "unopened/unseen" notifications or "unarchived" notifications
  • Can be a dot like:
  • Many other formatting and positioning customizations available

Counter (on existing elements)

Apply the same counter badge on an existing element to notify users of unread messages.

<NotificationCounter>
<Button>Counter</Button>
</NotificationCounter>

Feed

The feed component provides a larger feed for browsing notifications. Notifications within the feed can also be clicked on to direct to links or pages, if any were set within the Notification template.

<NotificationFeed infiniteScrollHeight={300} />

Example:



Notification Preferences Center

Preferences Popup

Our notification preferences popup allows users to set their preferences with your app. The component contains all your templates, and sliders for users to opt-in and out of notifications, and per channel where applicable.

const [preferencesPopupVisibility, setPreferencesPopupVisiblity] = React.useState(false);
<button onClick={() => setPreferencesPopupVisiblity(true)}>
Preferences Popup
</button>
<NotificationPreferencesPopup
open={preferencesPopupVisibility}
onClose={() => {
setPreferencesPopupVisiblity(false);
}}
/>


Preferences Inline

Alternatively, we also offer an inline component for user preferences. Ideal for options & settings pages.

<NotificationPreferencesInline />

Example:



UI Customizations

Customizing the Button

Make our button fit in - or stand out. You can customize our button using the following parameters:

ParameterTypeDescription
buttonIconSizenumberDetermines the size of the icon used for the button.
buttonHeightnumberDetermines the height of the button.
buttonWidthnumberDetermines the width of the button.
iconColorstringDetermines the color of the icon used for the button.
<NotificationPopup buttonIconSize={30} buttonHeight={50} buttonWidth={50} />

Customizing the Button (Launcher)

The launcher component takes additional parameters, allowing you to better position the button on your app.

ParameterTypeDescription
offsetXnumber or stringDetermine a horizontal offset for your popup launcher.
offsetYnumber or stringDetermine a vertical offset for your popup launcher.
positionstring: TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHTDetermine which corner you want the popup launcher to anchor on.
<NotificationLauncher buttonIconSize={30} offsetX={200} offsetY={100} />

Customizing the Header

You can change the header of your notifications to take your own custom React Component. You can modify the "Notifications" header found in the popup, feed, and launcher.

<NotificationPopup
header={{
title: <>"Notification"</>
}}
/>

Customizing the Popup

Customize out popup to be the right fit for your app. Our Popup can be customized using these parameters:

ParameterTypeDescription
countReactNode["count"]Modify the appearance of the count on your popup. Behaves similarly to the Counter.
filterstring: ALL, UNARCHIVEDFilter which notifications appear. Set to ALL by default.
imageShapestring: circle, squareDetermines the shape of images in the popup feed. Set to circle by default.
pagePositionstring: top, bottomDetermines whether the popup will render page buttons at the top or bottom of the component. Set to top by default.
pageSizenumberRequires pagination set to PAGINATED. Determines the amount of notifications shown per page.
paginationstring: INFINITE_SCROLL,PAGINATEDChoose between a single page or multiple pages for your inbox. Set to INFINITE_SCROLL by default
renderersobject: {notification: NotificationProps["renderer"], NotificationExtra["extraRenderer"]Allows you to render custom & additional content.
styleRecord<SemanticDOM, CSSProperties>Pass in your styles to match our popup with your design
unreadBadgePropsReactNodeModify the unread badge. Behaves similarly to the Counter.
<NotificationPopup
imageShape="circle"
pagination="PAGINATED"
pageSize={4}
pagePosition="bottom"
/>

Customizing the Feed

Customize the feed using these parameters:

ParameterTypeDescription
filterReactNodeFilter the notifications that appear in your feed using a custom component.
headerReactNodePass in a custom React component as your header.
imageShapestring: circle, squareRender images with the feed in a circle or square. Set to circle by default.
infiniteScrollHeightnumberDetermine a height for the feed component.
pagePositionstring: bottom, topSet a location for the page buttons. Requires pagination to be set to PAGINATED. Set to top by default.
pageSizenumberAdjust the number of notifications displayed per page. Requires pagination to be set to PAGINATED.
paginationstring: INFINITE_SCROLL, PAGINATEDDetermines whether your feed is paginated, or one page for all notifications. Set to PAGINATED by default.
renderersobject: { notification: NotificationProps["renderer"] }Render additional content within your feed.
styleRecord<SemanticDOM, CSSProperties>Pass in your styles to match our feed with your design.
<NotificationFeed
pagination="PAGINATED"
pageSize={6}
pagePosition="bottom"
infiniteScrollHeight={300}
/>

Unread Badge

You can customize the unread badge using these parameters and features:

ParameterTypeDescription
colorstring: blue, cyan, gold, green, lime, magenta, orange, pink, purple, red, yellow, volcano, geekblueCustomize the color for your badge icon.
countReactNodeSet a value to display in the badge.
classNamesRecord<SemanticDOM, string/>Set class names for your badge component.
dotbooleanDisplay a plain dot instead of your counter.
offset[number, number]Set an alternative location for the badge.
overflowCountnumberBadge displays a + beside your number when notifications exceed that amount.
showZerobooleanShow a 0 on the badge when there are no new notifications.
sizedefault, smallModify the size of the unread badge.
statussuccess, processing, default, error, warningGive notifications a colored badge noting message status.
stylesRecord<SemanticDOM, CSSProperties/>Use Semantic DOM style to modify your badge.
textReactNodeSets the badge text to status if status has been set.
titlestringSet hover text for your badge.
<NotificationCounter
color="lime"
count={(n) => {
return n.notificationId === 'inapp_notifications' && !n.archived;
}}
dot={false}
size="small"
>
<button>Counter</button>
</NotificationCounter>

Pagination

You can use this to set up pages for your feed. Design scrollable, interactive inbox for your users through our component. Your feed can be modified further using these arguments:

ParameterTypeDescription
borderedbooleanToggle a border for your feed. Set to false by default.
dataSourceany[]Set a data source for your feed.
footerReactNodeRender a footer for your feed.
gridobjectGive your feed grid properties via JSON.
headerReactNodeRender a header for your feed.
itemLayouthorizontal, verticalDetermine the layout of your feed.
loadingboolean+Show a loading symbol within the component when fetching your dataSource. False by default.
loadMoreReactNodeRender a component to load more data for yuor feed.
localeobjecti18n text or empty text.
paginationboolean, objectSet and modify pagination for your feed. Set to false by default.
renderItem(item) => ReactNodeDefine a custom list when using dataSource.
rowKeykeyof X, (item: X) => React.KeyDetermine an item's key value. Can be either a unique value or a function that returns a value.
sizesmall, default, largeAdjust the size and spacing of your feed.
splitbooleanToggle a visual separator for individual notifications in your feed. Set to false by default.

Logical Customizations

Count

This refers to what notifications are counted in the counters or unread badges. You can use an existing mode or count the notifications by your own custom function:

  • COUNT_UNOPENED_NOTIFICATIONS (default): only counts notifications that are never seen/opened. Once the user opens the notification popup, the count will be reset to zero.
  • COUNT_UNARCHIVED_NOTIFICATIONS: only counts the notifications that are not archived. The count will change when the user marks notifications as archived.
  • Custom: you can create your own function to count the notifications. The example code below counts notifications that belong to the welcome_notification category and are not archived.
<NotificationPopup
count={(n) => {
return n.notificationId === 'welcome_notification' && !n.archived;
}}
/>

Filters

This refers to which notifications are rendered in the pre-existing popup, feed, ... components. You can filter notifications via existing modes or create your own custom function:

  • ALL (default): renders all notifications
  • UNARCHIVED: renders only notifications that are not archived
  • Custom: The example code below filters notifications that belong to the welcome_notification category and are not archived.
<NotificationPopup
count={(n) => {
return n.notificationId === 'welcome_notification' && !n.archived;
}}
/>

Customizing each Notification

Headless (build your own UI)

You can build your own UI by reading the data inside our React Context object. It includes all our notification objects, users preferences, and functions for updating notification states. You can use these to build any notification UI you need.

Setup

Inside the components wrapped in our NotificationAPIProvider, you can access the context object using the useNotificationAPIContext hook:

export const MyComponent: React.FC = () => {
const notificationapi = NotificationAPIProvider.useNotificationAPIContext();

return (
<Button
onClick={() => {
console.log(notificationapi.notifications);
}}
>
Click to log notifications
</Button>
);
};

Accessing notification data

notificationapi.notifications;

Accessing user preferences

notificationapi.preferences;

Updating user preferences

notificationapi.updateDelivery(
notificationId,
channel,
delivery,
subNotificationId?
)

Marking loaded notifications as opened/seen

notificationapi.markAsOpened();

Marking notifications as archived

// to mark all as archived:
notificationapi.markAsArchived('ALL');

// to mark invididual notifications as archived:
notificationapi.markAsArchived(['trackingId1', 'trackingId2']);

Marking a notification as clicked

notificationapi.markAsClicked('trackingId');

asking for web push opt in

notificationapi.setWebPushOptIn(true);

Concepts

How does it work?

You trigger the API from the back-end and we store the notification. When users sign into the app, the sdk will pull their notification.

Websocket

We have our own websocket for sending & receiving new notifications. With this websocket, users will automatically receive new notifications without needing to refresh their pages. Since the websocket is automatically in place, developers don't need to do anything to implement this.

In-App Notification Object

The in-app notification object takes several arguments.

ParameterTypeDescription
actioned1stringComing soon! Assign a function for button 1 in your template, if a custom button has been assigned.
actioned2stringComing soon! Assign a function for button 2 in your template, if a custom button has been assigned.
archivedstringDetermines if the notification is considered as archived. Also referred to as "resolved".
bodyReactNodeUsed to add your custom UI to your notification.
clickedstringDetermines if the notification has been clicked on by the recipient.
datestringUsing ISO 8607 formatting (YYYY-MM-DD), give your notification a date.
expDatenumberGive your notification a TTL by passing in a Unix timestamp (in sencods). The notification will expire once the timestamp has passed.
idstringYour notification's tracking ID. Not the same as notificationId.
imageURLstringEmbed an image within your notification.
notificationIdstringThe ID for your notification's template.
openedstringDetermines if the notification has been opened by the recipient. Notifications are considered opened if rendered onscreen for the recipient.
parametersRecord<string, unknown>Mergetags. Give your notification mergetags/props that can pass values into matching mergetags within your notification templates.
redirectURLstringGive your notification a link to send users to upon clicking.
repliesobject: { date: string, message: string }[],Coming soon - Contains user comments/replies to the notification if enabled.
titlestringA title for your in-app notification.

identify

Stores the end-user information for a given user.

notificationapi
.getClient()
.identify({ id: '' }) // or mention the userId passed in the provider
.then((result) => console.log(result));