Push Notifications
Intermediate
Topic 7 of 18
Push Notifications
Building on Firebase Cloud Messaging, this tutorial covers how to properly handle and respond to push notifications in different app states within your React Native application.
Handling Foreground Notifications
javascript
import messaging from '@react-native-firebase/messaging';
useEffect(() => {
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
Alert.alert(remoteMessage.notification.title, remoteMessage.notification.body);
});
return unsubscribe;
}, []);
Handling Background Notifications
javascript
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Message handled in the background:', remoteMessage);
});
Handling Notification Taps
javascript
messaging().onNotificationOpenedApp((remoteMessage) => {
navigation.navigate(remoteMessage.data.screen);
});
Handling Notifications from a Quit State
javascript
useEffect(() => {
messaging().getInitialNotification().then((remoteMessage) => {
if (remoteMessage) {
navigation.navigate(remoteMessage.data.screen);
}
});
}, []);
Displaying Custom Notification UI
For foreground notifications, since the OS does not automatically display a system notification, libraries like Notifee can be used to show a custom, richly styled in-app notification.
bash
npm install @notifee/react-native
Setting Notification Channels (Android)
javascript
await notifee.createChannel({ id: 'default', name: 'Default Channel' });
Conclusion
Properly handling push notifications across foreground, background, and quit app states ensures users receive and can act on important notifications regardless of how they are currently using your React Native application.