React-native push-notification locally and generate token for remote notification.



Hello, Today I have created demo application for notification in react-native. I have used react-native-push-notification. In this project, I have sent locally notification and generate token for remote notification. To see the demo, click here.  Follow the following steps.



Step 1:- Create a new project.

react-native init pushNotification

Note :- You can change project name according to yourself.

Step 2:- Install react-native-push-notification

npm install –save react-native-push-notification

Step 3:- Link the react-native-push-notification.

react-native link

Note :- In android you still need to link manually in android/app/build.gradle,  AndroidManifest.xml,  android/settings.gradle.
You can manually link from here.  Don’t forget to replace${applicationId} with your own applicationId in AndroidManifest.xml file.

Step 4:- Replace index.js with following code.

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('pushNotification', () => App);

Step 5:– Replace the code of App.js

import React, { Component } from 'react';
import { View, Text, StyleSheet, Picker, AppState, Platform, Modal, TouchableOpacity } from 'react-native';
import PushNotificationController from './App/pushNotificationController';
import PushNotification from 'react-native-push-notification';
import styles from './style'

export default class App extends Component {
  constructor(props) {
    super(props);

    this.handleStateChange = this.handleStateChange.bind(this);
    this.state = {
      time: 5,
      showModal: false,
    };
  }

  componentDidMount() {
    AppState.addEventListener('change', this.handleStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this.handleStateChange);
  }

  handleStateChange(appState) {
    if (appState === 'background') {
      let date = new Date(Date.now() + (this.state.time * 1000));

      if (Platform.OS === 'ios') {
        date = date.toISOString();
      }

      PushNotification.localNotificationSchedule({
        message: "Hello Friend, you have new notification",
        title: "My App Title",
        subText: "Sub Title of notification ",
        color: "red",
        date,
      });
    }
  }

  render() {
    return (
      <View style={styles.container}>
       <Text style={styles.titleMessage}>
          Select notification time
        </Text>
        <TouchableOpacity onPress={() => this.setState({showModal: true})} style={styles.textButton}>
          <Text>Select Time</Text>
           <Text>Selected Time {this.state.time}</Text>
         </TouchableOpacity>
         <Modal
           transparent={true}
           visible={this.state.showModal}
           animationType={'none'}
           onRequestClose={() => this.closeModal()}
           >
             <View style={styles.modalContainer}>
             <View style={styles.modalSubContainer}>
               <TouchableOpacity onPress={() => this.setState({time: "5", showModal: false})}>
                 <Text style={styles.time}>5 seconds</Text>
               </TouchableOpacity>
               <TouchableOpacity onPress={() => this.setState({time: "10", showModal: false})}>
                 <Text style={styles.time}>10 seconds</Text>
               </TouchableOpacity>
               <TouchableOpacity onPress={() => this.setState({time: "15", showModal: false})}>
                 <Text style={styles.time}>15 seconds</Text>
               </TouchableOpacity>
               <TouchableOpacity onPress={() => this.setState({showModal: false})} style={styles.crossIcon}>
                  <Text>Close</Text>
                </TouchableOpacity>
             </View>
            </View>
           </Modal>
         <PushNotificationController />
       </View>
    );
  }
}

Note:- PushNotification.localNotification(details: Object) is used for local notification which have message, title subText, color etc property.

PushNotification.localNotificationSchedule({
        message: "Hello Friend, you have new notification",
        title: "My App Title",
        subText: "Sub Title of notification ",
        color: "red",
        date,
      });




Step 6:– Create a new file named it style.js

import {
  StyleSheet,
  Dimensions
} from 'react-native';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  titleMessage: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  time: {
    margin: 10,
  },
  picker: {
    width: 100,
  },
  wrapStyle: {
    alignSelf: 'flex-end',
    padding: 10,
  },
  modalContainer: {
    position: 'absolute',
    backgroundColor: '#000000af',
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
    alignItems: 'center',
    justifyContent: 'center',
  },
  crossIcon: {
    position: 'absolute',
    top: 0,
    right: 3,
    zIndex: 99,
  },
  modalSubContainer: {
    justifyContent: 'center',
    height: deviceHeight / 4.4,
    width: deviceWidth - 50,
    backgroundColor: "#fff",
  },
});
module.exports = styles;

Step 7:– Create a new file /App/pushNotificationController.js

import React, { Component } from 'react';
import PushNotification from 'react-native-push-notification';

export default class PushNotificationController extends Component {
  componentDidMount() {
    PushNotification.configure({
        // onRegister: function(token) {
        //     console.log( 'TOKEN:', token );
        // },
        onNotification: function(notification) {
            console.log( 'NOTIFICATION:', notification );
        },
        //senderID: "your sender ID",
    });
  }

  render() {
    return null;
  }
}

In this file i have used two function.
1. onNotification function called when i clicked on notification which give notification id etc.
2. onRegister function is used to generate notification token and info of device which is used in remote notification. (This can be tested only on device not on simulator)

Note:- To use the remote notification, senderID  (GCM)  is required. (it is required only for android not for ios)

If there is any issue in configuration, feel free to comment.

Sunil Yadav

About Sunil Yadav

Hi, This is Sunil Yadav, I am full stack dev. I have a passion for learning and sharing my knowledge with others as publicly as possible.

View all posts by Sunil Yadav →

Leave a Reply

Your email address will not be published. Required fields are marked *