Notificaciones locales en React Native

Notificaciones locales en React Native

Hola a todos. En el día de hoy les presento cómo realizar notificaciones locales en los dispositivos móviles con react-native, sin la necesidad de utilizar servicios como Firebase u Onesignal.

Paso 1: Crear aplicación

npx react-native init miProyecto

Paso 2: Instalar dependencias

npm install @notifee/react-native

Paso 3: Importar librería

import notifee from '@notifee/react-native';

Paso 4: Mostrar notificaciones

const displayNotification = async () => {
  const channelId = await notifee.createChannel({
    id: 'primary',
    name: 'Primary Channel',
  });

  await notifee.displayNotification({
    title: '<b>Title lorem ipsum</b',
    body: 'Qui officia commodo occaecat est incididunt sit incididunt.',
    android: {
      channelId,
    },
  });
};

Paso 5: Capturar acciones

useEffect(() => {
  return notifee.onForegroundEvent(({type, detail}) => {
    switch (type) {
      case EventType.DISMISSED:
        console.log('dismissed notification');
        break;
      case EventType.PRESS:
        console.log('pressed notification');
        break;
    }
  });
}, []);

Paso 6: Ejecución

npm start

npx react-native run-android

The Code :)

import React, {useEffect} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import notifee, {EventType} from '@notifee/react-native';

function App(props) {
  const displayNotification = async () => {
    const channelId = await notifee.createChannel({
      id: 'primary',
      name: 'Primary Channel',
    });

    await notifee.displayNotification({
      title: '<b>Title lorem ipsum</b',
      body: 'Qui officia commodo occaecat est incididunt sit incididunt.',
      android: {
        channelId,
      },
    });
  };

  useEffect(() => {
    return notifee.onForegroundEvent(({type, detail}) => {
      switch (type) {
        case EventType.DISMISSED:
          console.log('dismissed notification');
          break;
        case EventType.PRESS:
          console.log('pressed notification');
          break;
      }
    });
  }, []);

  return (
    <View style={styles.container}>
      <Button
        title="Display Notification"
        onPress={() => displayNotification()}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;