Cours React Native · Module 7: Notifications

Notifications locales

2 min de lecture ·
Dans cette leçon3

Les notifications locales ne nécessitent pas de serveur - elles sont générées directement sur l'appareil.

Envoyer une notification locale

import * as Notifications from 'expo-notifications';

// Notification immédiate
async function sendLocalNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Message de l\'Atlantide !',
      body: 'Poséidon a une nouvelle mission pour toi.',
      data: { screen: 'Tasks', taskId: '123' },
      sound: true,
      badge: 1,
    },
    trigger: null, // null = immédiat
  });
}

// Notification différée
async function scheduleNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Rappel',
      body: 'N\'oublie pas ton entraînement !',
    },
    trigger: {
      seconds: 60, // dans 60 secondes
    },
  });
}

// Notification à une heure précise
async function scheduleDailyReminder() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Bonjour !',
      body: 'C\'est l\'heure de ta séance de natation matinale.',
    },
    trigger: {
      hour: 8,
      minute: 0,
      repeats: true, // quotidien
    },
  });
}

// Notification à une date précise
async function scheduleEventReminder(eventDate: Date) {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Événement demain !',
      body: 'Le Festival de Poséidon commence demain.',
    },
    trigger: eventDate,
  });
}

Annuler des notifications

// Annuler une notification précise
const notificationId = await Notifications.scheduleNotificationAsync({...});
await Notifications.cancelScheduledNotificationAsync(notificationId);

// Annuler toutes les notifications programmées
await Notifications.cancelAllScheduledNotificationsAsync();

// Obtenir la liste des notifications programmées
const scheduled = await Notifications.getAllScheduledNotificationsAsync();

Gérer le badge

// Définir le badge
await Notifications.setBadgeCountAsync(5);

// Obtenir le badge actuel
const count = await Notifications.getBadgeCountAsync();

// Effacer le badge
await Notifications.setBadgeCountAsync(0);

Les notifications locales sont idéales pour les rappels et les alertes hors ligne !

Code de cette leçon : App.tsx
import { View, Text, Button, StyleSheet } from 'react-native';
import * as Notifications from 'expo-notifications';

// Notification locale après 1 heure
async function scheduleReminderInOneHour() {
  // TODO : appelle Notifications.scheduleNotificationAsync({ ... })
  // content doit inclure title et body
  // définis trigger à { seconds: 3600 } (1 heure)
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Rappel Atlantide',
      // TODO : ajoute body avec le texte du rappel
      body: '',
    },
    // TODO : définis trigger à 1 heure (3600 secondes)
    trigger: null,
  });
}

// Notification immédiate (trigger: null)
async function sendNow() {
  // TODO : envoie une notification immédiatement (trigger: null)
}

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Rappels</Text>
      <Button title="Rappeler dans une heure" onPress={scheduleReminderInOneHour} />
      <Button title="Envoyer maintenant" onPress={sendNow} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1a5276', gap: 16 },
  title: { fontSize: 24, color: '#fff' },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Comment envoyer une notification locale immédiate ?

  2. 2. Comment programmer une notification dans 60 secondes ?

Voici 2 des 4 questions de cette leçon. Réponds aux autres dans le jeu.

Tâches pratiques dans le jeu

  • Clique dans l'ordre

    Clique dans l'ordre sur les éléments du contenu de la notification :

  • Tri horizontal

    Ordonne le trigger d'un rappel quotidien à 8h00 :

  • Éditeur de code

    Complète le code de la notification programmée.

  • Clique dans l'ordre

    Clique sur les éléments de définition du badge :

Articles utiles