0
0
React Nativemobile~10 mins

Push notifications (expo-notifications) in React Native

Choose your learning style9 modes available
Introduction

Push notifications let your app send messages to users even when they are not using the app. This helps keep users informed and engaged.

To remind users about an upcoming event or appointment.
To alert users about new messages or updates.
To send promotional offers or news.
To notify users about important app changes or alerts.
Syntax
React Native
import * as Notifications from 'expo-notifications';

// Request permission
const permission = await Notifications.requestPermissionsAsync();

// Get device push token
const token = await Notifications.getExpoPushTokenAsync();

// Listen for notifications
Notifications.addNotificationReceivedListener(notification => {
  console.log(notification);
});

Always ask user permission before sending notifications.

The push token uniquely identifies the device for sending notifications.

Examples
This asks the user to allow notifications.
React Native
const permission = await Notifications.requestPermissionsAsync();
This gets the device token needed to send push notifications.
React Native
const token = await Notifications.getExpoPushTokenAsync();
This listens for notifications received while the app is open.
React Native
Notifications.addNotificationReceivedListener(notification => {
  console.log(notification);
});
Sample App

This app asks permission for notifications, gets the device token, and shows it on screen. When you press the button, it sends a test notification to your device. Notifications received while the app is open show their title and body below the button.

React Native
import React, { useEffect, useState } from 'react';
import { View, Text, Button, Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);

  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    const subscription = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    return () => subscription.remove();
  }, []);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Your Expo Push Token:</Text>
      <Text selectable>{expoPushToken}</Text>
      <View style={{ marginTop: 20 }}>
        <Button
          title="Press to Send Test Notification"
          onPress={async () => {
            await sendPushNotification(expoPushToken);
          }}
        />
      </View>
      {notification ? (
        <View style={{ marginTop: 20 }}>
          <Text>Last Notification:</Text>
          <Text>{notification.request.content.title}</Text>
          <Text>{notification.request.content.body}</Text>
        </View>
      ) : null}
    </View>
  );
}

async function sendPushNotification(expoPushToken) {
  const message = {
    to: expoPushToken,
    sound: 'default',
    title: 'Test Notification',
    body: 'This is a test push notification',
    data: { someData: 'goes here' },
  };

  await fetch('https://exp.host/--/api/v2/push/send', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Accept-Encoding': 'gzip, deflate',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(message)
  });
}

async function registerForPushNotificationsAsync() {
  let token;
  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  return token;
}
OutputSuccess
Important Notes

Push notifications require a physical device; they do not work on simulators or emulators.

Always handle user permission carefully and explain why notifications are useful.

Use notification channels on Android for better control of notification behavior.

Summary

Push notifications keep users informed even when the app is closed.

Use expo-notifications to request permission, get tokens, and listen for notifications.

Test notifications by sending messages to the device token from your app or server.