Mastering Push Notifications in React Native: A Comprehensive Guide with Examples

Bhuvin
5 min readJan 28, 2024

--

Introduction

Push notifications are an essential feature for mobile apps, allowing developers to engage users with timely updates. In this comprehensive guide, we’ll explore the process of setting up and handling push notifications in a React Native app using Firebase Cloud Messaging (FCM) as an example.

Why Push Notifications?

Push notifications provide a direct communication channel between apps and users, enabling real-time updates, personalized content, and re-engagement opportunities. Integrating push notifications into your React Native app can significantly improve user retention and interaction.

Setting Up Push Notifications with FCM

Android Configuration:

1. Configure Firebase for Android:

  • Go to the Firebase Console and create a new project.
  • Add an Android app to your Firebase project, providing the required details.
  • Download the google-services.json file and place it in the android/app directory of your React Native project.

2. Update Android Manifest:

Open android/app/src/main/AndroidManifest.xml and add the following within the <application> tag:

<application>
<!-- ... -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_notification_icon" />
<!-- ... -->
</application>

Make sure to replace ic_notification_icon with the name of your custom notification icon.

3. Update build.gradle:

Open android/app/build.gradle and add the following dependency:

implementation 'com.google.firebase:firebase-messaging:23.0.0'

Sync your project after making these changes.

iOS Configuration:

1. Configure Firebase for iOS:

In the Firebase Console, add an iOS app to your project and provide the required details. Download the GoogleService-Info.plist file and add it to the ios directory of your React Native project.

2. Set up APNs:

3. Enable Capabilities:

Open your Xcode project (located in the ios directory) using the .xcworkspace file. In Xcode, select your project in the left navigator, go to the "Signing & Capabilities" tab, and enable "Push Notifications" and "Background Modes" with "Remote notifications" checked.

4. Update AppDelegate.m:

Open ios/AppDelegate.m and add the following imports and methods:

#import <Firebase.h>
// ...
@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
[FIRApp configure];
// ...
return YES;
}
// For handling notifications while the app is in the foreground
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[FIRMessaging didReceiveMessage:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
@end

React Native Code:

Now, in your React Native code, use the @react-native-firebase/messaging library:

npm install @react-native-firebase/app @react-native-firebase/messaging

In your entry file (e.g., index.js), initialize Firebase:

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
import { name as appName } from './app.json';
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background message handled:', remoteMessage);
});
AppRegistry.registerComponent(appName, () => App);

Handle foreground messages and notification interactions in your React Native components:

import messaging from '@react-native-firebase/messaging';
messaging().onMessage(remoteMessage => {
console.log('Foreground message:', remoteMessage);
// Display the notification to the user
});
messaging().onNotificationOpenedApp(remoteMessage => {
console.log('App opened by notification while in foreground:', remoteMessage);
// Handle notification interaction when the app is in the foreground
});
messaging().getInitialNotification().then(remoteMessage => {
console.log('App opened by notification from closed state:', remoteMessage);
// Handle notification interaction when the app is opened from a closed state
});

Remember to adapt the examples to fit your specific use case, including customizing notification content and handling user interactions according to your app’s requirements.

Best Practices for Push Notifications

  1. Personalization:
  • Personalize notifications based on user preferences and behavior.
const personalizedMessage = `Hello, ${user.displayName}!`; messaging().send({   ...notification,   notification: {     body: personalizedMessage,   }, });

2. Timing and Frequency:

  • Schedule notifications with proper timing.
const futureDate = new Date();
futureDate.setMinutes(futureDate.getMinutes() + 10); // 10 minutes from now
messaging().scheduleNotification({
...notification,
schedule: {
at: futureDate,
},
})

3. Localization:

  • Support multiple languages and locales.
const localizedMessage = {   en: 'Hello!',   es: '¡Hola!', };  messaging().send({   ...notification,   notification: {     body: localizedMessage[user.language] || localizedMessage.en,   }, });

4. Analytics and A/B Testing:

  • Track notification clicks.
messaging().onNotificationOpenedApp(remoteMessage => {   // Track the notification click event   analytics().logEvent('notification_clicked', { ...remoteMessage }); });

5. Permission Handling:

  • Request permission.
const requestPermission = async () => {   const authStatus = await messaging().requestPermission();   console.log('Permission status:', authStatus); };

Conclusion

With this comprehensive guide, you’ve gained a solid understanding of setting up and working with push notifications in your React Native app. Leveraging the capabilities of Firebase Cloud Messaging, along with best practices for personalization and user engagement, you can now create a seamless and effective push notification experience for your users. As you continue to refine and customize your implementation, your React Native app will be well-equipped to keep users informed and engaged in real-time.

Important links for your reference:

Below are important links and resources that you can refer to for implementing push notifications in a React Native app using Firebase Cloud Messaging (FCM) and other related topics:

1. Firebase Console:
— [Firebase Console](https://console.firebase.google.com/): Set up your Firebase project and configure FCM.

2. React Native Firebase Documentation:
— [React Native Firebase Documentation](https://rnfirebase.io/): Official documentation for React Native Firebase, including Cloud Messaging.

3. Firebase Cloud Messaging (FCM) Documentation:
— [Firebase Cloud Messaging Documentation](https://firebase.google.com/docs/cloud-messaging): Learn more about FCM features, integration, and best practices.

4. Android Icon Guidelines:
— [Android Iconography Guidelines](https://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar): Guidelines for Android notification icons.

5. Apple Developer Console:
— [Apple Developer Console](https://developer.apple.com/): Access the Apple Developer Console for iOS-related configurations.

6. Handling Notifications in Foreground and Background in React Native:
— [React Native Firebase — Handling Notifications](https://rnfirebase.io/messaging/notifications): Guide on handling notifications in React Native Firebase.

7. Background Notifications in React Native:
— [React Native Firebase — Background Notifications](https://rnfirebase.io/messaging/usage#background-messages): Understanding and handling background messages.

8. React Native Push Notification Library:
— [React Native Push Notification Library](https://github.com/invertase/react-native-firebase/tree/master/packages/messaging): GitHub repository for the React Native Firebase Messaging package.

9. React Native Permissions:
— [React Native Permissions Library](https://github.com/react-native-permissions/react-native-permissions): A library for handling permissions in React Native.

10. React Native Analytics:
— [React Native Analytics](https://github.com/react-native-analytics/react-native-analytics): A library for integrating analytics into your React Native app.

Remember to check for the latest updates and changes in the documentation and repositories. These resources should provide a solid foundation for implementing push notifications in your React Native app and enhancing the overall user experience.

--

--