0
0
React Nativemobile~20 mins

Push notifications with FCM in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Push Notification Demo
This screen registers the app for Firebase Cloud Messaging (FCM) push notifications and displays the latest notification message received.
Target UI
-------------------------
| Push Notification Demo |
-------------------------
|                       |
| Latest message:       |
|                       |
| [No messages yet]     |
|                       |
|-----------------------|
| [Request Permission]  |
|-----------------------|
Request user permission for push notifications
Register device with FCM to receive push tokens
Listen for incoming push notifications while app is in foreground
Display the latest notification message on screen
Add a button to manually request notification permission
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import messaging from '@react-native-firebase/messaging';

export default function PushNotificationDemo() {
  const [message, setMessage] = useState('No messages yet');

  useEffect(() => {
    // TODO: Request permission and listen for messages
  }, []);

  const requestPermission = async () => {
    // TODO: Request notification permission
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Push Notification Demo</Text>
      <Text style={styles.label}>Latest message:</Text>
      <Text style={styles.message}>{message}</Text>
      <Button title="Request Permission" onPress={requestPermission} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 24, marginBottom: 20 },
  label: { fontSize: 18, marginBottom: 10 },
  message: { fontSize: 16, marginBottom: 30, fontStyle: 'italic' }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet, Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';

export default function PushNotificationDemo() {
  const [message, setMessage] = useState('No messages yet');

  useEffect(() => {
    async function setupFCM() {
      const authStatus = await messaging().requestPermission();
      const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;

      if (enabled) {
        const token = await messaging().getToken();
        console.log('FCM Token:', token);
      } else {
        Alert.alert('Permission denied', 'Push notifications permission was not granted');
      }
    }

    setupFCM();

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      if (remoteMessage.notification) {
        setMessage(remoteMessage.notification.title + ': ' + remoteMessage.notification.body);
      }
    });

    return unsubscribe;
  }, []);

  const requestPermission = async () => {
    try {
      const authStatus = await messaging().requestPermission();
      if (authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL) {
        Alert.alert('Permission granted', 'You will receive push notifications');
      } else {
        Alert.alert('Permission denied', 'Push notifications permission was not granted');
      }
    } catch (error) {
      Alert.alert('Error', 'Failed to request permission');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Push Notification Demo</Text>
      <Text style={styles.label}>Latest message:</Text>
      <Text style={styles.message}>{message}</Text>
      <Button title="Request Permission" onPress={requestPermission} accessibilityLabel="Request push notification permission button" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 24, marginBottom: 20 },
  label: { fontSize: 18, marginBottom: 10 },
  message: { fontSize: 16, marginBottom: 30, fontStyle: 'italic' }
});

This app uses the @react-native-firebase/messaging library to handle push notifications with Firebase Cloud Messaging (FCM). In the useEffect hook, it requests notification permission from the user and obtains the FCM token if permission is granted. It also sets up a listener with messaging().onMessage to receive notifications when the app is in the foreground and updates the displayed message accordingly.

The Request Permission button allows the user to manually request notification permission again if needed. Alerts inform the user about permission status. The UI shows the latest notification message or a placeholder if none received yet.

This simple setup helps beginners understand how to integrate push notifications in React Native apps using FCM.

Final Result
Completed Screen
-------------------------
| Push Notification Demo |
-------------------------
|                       |
| Latest message:       |
|                       |
| New Offer: 50% off!   |
|                       |
|-----------------------|
| [Request Permission]  |
|-----------------------|
When the app starts, it asks for notification permission automatically.
If a push notification arrives while the app is open, the message text updates to show the notification title and body.
Tapping the 'Request Permission' button asks the user for notification permission again.
Alerts show whether permission was granted or denied.
Stretch Goal
Add a feature to display the FCM token on screen after permission is granted.
💡 Hint
Store the token in a state variable and show it below the latest message text.