React Native course ยท Module 7: Notifications

expo-notifications - Introduction

2 min read ยท
In this lesson3

Welcome to the Siren Tower! Here you will learn how to send notifications - like sirens summoning the residents of Atlantis.

Installation

npx expo install expo-notifications expo-device expo-constants

Configuration (app.json)

{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./assets/notification-icon.png",
          "color": "#1a5276",
          "sounds": ["./assets/sounds/notification.wav"]
        }
      ]
    ],
    "android": {
      "useNextNotificationsApi": true
    }
  }
}

Basic Configuration

import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import { Platform } from 'react-native';

// Configure how to display notifications when app is active
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowBanner: true,
    shouldShowList: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

// Register for push notifications
async function registerForPushNotificationsAsync() {
  let token;

  // Push notifications only work on real devices
  if (!Device.isDevice) {
    console.log('Push notifications require a physical device');
    return;
  }

  // Check/request permissions
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  if (finalStatus !== 'granted') {
    console.log('No notification permissions');
    return;
  }

  // Get Expo Push Token
  token = await Notifications.getExpoPushTokenAsync({
    projectId: 'your-project-id', // from app.json
  });

  // Android: set notification channel
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#1a5276',
    });
  }

  return token;
}

expo-notifications is the official Expo library for handling notifications!

Code for this lesson: App.tsx
import { useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet, Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

// Configure how notifications show when the app is in the foreground
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

// Register for an Expo Push Token
async function registerForPushNotificationsAsync(): Promise<string | undefined> {
  // Push notifications only work on a physical device
  if (!Device.isDevice) {
    console.log('Push requires a physical device');
    return;
  }

  // TODO: check current permissions with Notifications.getPermissionsAsync()
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  // TODO: if not granted, request permissions with requestPermissionsAsync()
  if (existingStatus !== 'granted') {
    // const { status } = ...
  }

  if (finalStatus !== 'granted') {
    console.log('No notification permissions');
    return;
  }

  // TODO: get the token with Notifications.getExpoPushTokenAsync()
  const token = '';

  // TODO (Android): set up the 'default' channel with setNotificationChannelAsync
  if (Platform.OS === 'android') {
    // await Notifications.setNotificationChannelAsync('default', { ... });
  }

  return token;
}

export default function App() {
  const [pushToken, setPushToken] = useState<string>('');

  useEffect(() => {
    registerForPushNotificationsAsync().then((token) => {
      if (token) setPushToken(token);
    });
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Siren Tower</Text>
      <Text style={styles.token}>{pushToken || 'No token'}</Text>
      <Button title="Register notifications" onPress={() => registerForPushNotificationsAsync()} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1a5276', padding: 20 },
  title: { fontSize: 24, color: '#fff', marginBottom: 16 },
  token: { fontSize: 12, color: '#aed6f1', marginBottom: 16, textAlign: 'center' },
});

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How to install expo-notifications?

  2. 2. What does Notifications.setNotificationHandler configure?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the notification handler configuration:

  • Horizontal ordering

    Arrange the push token retrieval:

  • Code editor

    Complete the push token registration code.

Useful articles