girishd / ReactPubNub

Example of PubNub + React Native app
5 stars 1 forks source link

React Native & PubNub

This is a quick example of getting PubNub running in a React Native project.

Step 1: Initialize React Native Project

react-native init ReactPubNub

1.InitReact.jpg

Step 2: Edit package.json to include PubNub dependencies

2.PackageJson.jpg

Step 3: Fetch PubNub SDK

npm install

Step 4: Import PubNub and intialize PubNub object

Modify index.android.js and index.ios.js

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import PubNub from 'pubnub'

class ReactPubNub extends Component {
  render() {
    return (
    );
  }
}

const pubnub = new PubNub({
    subscribeKey: "demo",
    publishKey: "demo",
    ssl: true
})

pubnub.addListener({
    message: function(message) {
        console.log(message);
        // handle message
    }
})

pubnub.subscribe({ 
    channels: ['girish'] 
});

AppRegistry.registerComponent('ReactPubNub', () => ReactPubNub);

Step 5: Run logger to view subscribed messages received by the device

react-native log-android

3.AndroidLog.jpg

Step 6: Profit