0% found this document useful (0 votes)
356 views1 page

Building A React Native Chat App - Part One - Basic Messaging - PubNub - by Krissanawat Kaewsanmuang - Medium

This document provides instructions for building a React Native chat app using PubNub and React Native Gifted Chat. It outlines setting up the development environment, installing necessary packages, implementing the Gifted Chat UI, and integrating PubNub for real-time messaging capabilities. Key steps include initializing a new React Native project, adding Gifted Chat for the chat interface, installing and configuring PubNub for publishing and subscribing to messages on channels, and connecting Gifted Chat messages to PubNub using the onSend callback.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
356 views1 page

Building A React Native Chat App - Part One - Basic Messaging - PubNub - by Krissanawat Kaewsanmuang - Medium

This document provides instructions for building a React Native chat app using PubNub and React Native Gifted Chat. It outlines setting up the development environment, installing necessary packages, implementing the Gifted Chat UI, and integrating PubNub for real-time messaging capabilities. Key steps include initializing a new React Native project, adding Gifted Chat for the chat interface, installing and configuring PubNub for publishing and subscribing to messages on channels, and connecting Gifted Chat messages to PubNub using the onSend callback.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Krissanawat Kaewsanmuang 908 Followers About Follow Sign in Get started

Building a React Native Chat App


— Part One: Basic Messaging |
PubNub
Krissanawat Kaewsanmuang Jun 24, 2019 · 6 min read

Welcome to part one of our series on building a mobile chat app with React
Native and PubNub. PubNub provides our realtime messaging chat APIs and
backend, and React Native Gifted Chat provides a complete chat UI for our
app.

In this case, we’ll use the PubNub React package, which is a wrapper for the
PubNub JavaScript SDK (v4). It simplifies the PubNub integrations with
React or React Native.

In the end, we’ll have a simple mobile group chat app that allows multiple
users to message one another in real-time. From there, we’ll continue adding
new chat features including message history, user online/offline status, and
typing indicators.

Requirements
Before we begin, make sure you have the following:

Node.js installed, along with NPM or yarn.

A PubNub account; this is where you’ll get your unique publish/subscribe


keys.

Two (or more) mobile devices to test the app.

Set Up
In this step, we’ll create a React Native project using the following command:

react-native init pubnubchatwithreactnative

Open the project folder named pubnubchatwithreactnative with VSCode or


your favorite code editor. Next, open an integrated terminal and run the
Android and iOS simulator by using the following code snippets:

react-native run-ios

# OR

react-native run-android

Note: It will take a considerable amount of time for the first build of the
React project. After the build, you will see the following on your Android
and iOS simulators.

UI: Installing the Gifted Chat UI Package


In this step, we are going to install the Gifted Chat package, providing us
with a complete chat UI. You can install react-native-gifted-chat with using
following commands:

npm install react-native-gifted-chat --save

# OR

yarn add react-native-gifted-chat

Grab the example code from the GitHub readme file and paste it into the
App.js file.

Next, import the GiftedChat component/module from the react-native-

gifted-chat package as shown in the code snippet below:

import { GiftedChat } from 'react-native-gifted-chat'

Replace the code in the default class with the following piece of code:

export default class App extends Component {


state = { messages: [], };

componentWillMount() {
this.setState({
messages: [
{ _id: 1, text: "Hello developer", createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any", }, }, ],
});
}

onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
})
);
}

render() {
return (
<GiftedChat messages={this.state.messages} onSend={messages =>
this.onSend(messages)} user={{ _id: 1, }} />
);
}

As seen in the code snippet above, the onSend() function is used for
collecting messages and concatenating with the previous message. You’ll see
it in the chat UI. The imported component GiftedChat is used to cover the
whole chat interface.

You need to save the code and refresh the simulators. You will see an example
of message.

Keep in mind that you will not be able to send messages because PubNub is
not yet implemented.

Messaging and Backend: Implementing PubNub


Now that we’ve got our UI ready to go, it’s time to make our chat app
interactive — allowing users to communicate in real-time. That’s where
PubNub comes in.

In this step, we’ll install the PubNub SDK. You can install the package using
the following commands.

Using NPM:

npm install pubnub-react --save

Using Yarn:

yarn add pubnub-react

Once the installation is done, you need to import the PubNubReact module
from the pubnub-react package as shown in the code:

import PubNubReact from 'pubnub-react';

Next, you can copy the example code from README file of the PubNub
React GitHub, and paste it into the App.js file of your project:

constructor(props) {
super(props); this.pubnub = new PubNubReact({ publishKey: 'YOUR
PUBLISH KEY', subscribeKey: 'YOUR SUBSCRIBE KEY' });
this.pubnub.init(this);
}

componentWillMount() {
this.pubnub.subscribe({ channels: ['channel1'], withPresence: true
});
this.pubnub.getMessage('channel1', (msg) => { console.log(msg); });
this.pubnub.getStatus((st) => { console.log(st);
this.pubnub.publish({ message: 'hello world from react', channel:
'channel1' }); });
}

componentWillUnmount() { this.pubnub.unsubscribe({ channels:


['channel1'] }); }

Next, add your unique pub/sub keys you got when you signed up for
PubNub. They’re available in your PubNub Admin Dashboard.

Save and re-run the simulator. To view the JavaScript console output, we
need to use Debug JS remotely.

You will now be able to see PubNub data in the browser console.

With that, the PubNub implementation is complete.

Next, we need to configure the chat channel using PubNub as set it up along
with Gifted Chat. Follow these simple steps:

Initialize PubNub (done)

Subscribe to channel name “channel1” with the SDK subscribe method.

Send a message to “channel1” with the publish method.

Get a message from a channel with getMessagemethod .

Putting It All Together


In this step, we bring the entire configuration together. We pass a message
from Gifted Chat to the PubNub publish() method. You can use the
example code from the code snippet below.

onSend(messages = []) {
this.pubnub.publish({ message: messages, channel: "Channel1", });
}

When the callback function onSend() is called, we will send a message to


Channel1.

To get a message from the channel in realtime, we use the following callback
to append previous state messages. Here is the code:

this.pubnub.getMessage("ReactChat", m => {
this.setState(previousState => ({ messages:
GiftedChat.append(previousState.messages, m["message"]), }));
});

All done! Let’s try it out by reloading the simulators. Now you should see the
following in your UI.

You will see chat messages appear in the UI, but all the messages appear on
the same side. We need to graphically separate messages sent from messages
received, to make it appear that two people are chatting.

<GiftedChat messages={this.state.messages} onSend={messages =>


this.onSend(messages)} user={{ _id: 0, }} />

This is because we haven’t set a new id when we open a new session. We need
to hard code the user ID.

Create a function in App.js for generating a random user ID, as shown in the
code snippet below.

randomid = () => { return Math.floor(Math.random() * 100); };

Set the variable and add it to the constructor function in App.js .

this.id = this.randomid();

Lastly, add the state and function to the GiftedChat HTML, as shown in the
code below.

<GiftedChat messages={this.state.messages} onSend={messages =>


this.onSend(messages)} user={{ _id: this.id, }} />

Now, reload the simulator and observe the result. You will see the chat
messages appear on the other side.

At last! We have completed the setup of a chat app using React Native along
with Gifted Chat and PubNub.

Wrapping Up
In this tutorial, we learned how to create a simple chat app with React Native
using Gifted Chat and PubNub. You’ve now got a basic mobile chat
application allowing users to send and receive messages in real-time.

Next step is to start adding additional chat features — message history,


typing indicators, user presence, etc. Keep an eye out for subsequent posts on
that!

All the code for this tutorial is available in my GitHub repo.

Originally published at https://www.pubnub.com on June 24, 2019.

Learn React Native - Best React Native Tutorials (2019) | gitconnected


The top 10 React Native tutorials - learn React Native for free.
Courses are submitted and voted on by developers…
gitconnected.com

JavaScript React Native Pub Sub Messaging Chat

268 1

More from Krissanawat Kaewsanmuang Follow

Defi farmer at https://maticdaily.news , l❤Polygon, MATIC Holder

Published in Heartbeat · Jun 21, 2019

Implementing Facebook login on Android


with React Native and Firebase

Image Source

This tutorial is a quick guide on how to integrate Facebook login with


Firebase while developing with React Native. By using Firebase and
Facebook login, you’ll be able to understand how to use and integrate
Firebase properly, as well as implement Facebook authentication along with
login. This process will also help developers learn a lot about Firebase, which
can be used as lightweight and easy-to-configure backend.
Nowadays, Facebook login has become important in a wide range of apps, as
it will provide users with an easier login approach than having to manually
enter credentials. …

Read more · 8 min read

71 1

Share your ideas with millions of readers. Write on Medium

Published in Bits and Pieces · Jun 20, 2019

Understanding JavaScript Hoisting


Learn to code better with a clearer understanding of JS hoisting

Hoisting is JS’s default behavior of defining all the declarations at the top of
the scope before code execution. One of the benefits of hoisting is that it
enables us to call functions before they appear in the code. JavaScript only
hoists declarations, not initializations. You can find the official
documentation here.
Tip: Turn reusable JS code into shared components with Bit (GitHub). Bit
helps everyone build modular JavaScript applications, easily share
components between projects and team, and build better & faster

Share reusable code components as a team · Bit


Easily share reusable components between projects and
applications to build faster as a team. Collaborate to develop…
bit.dev

Understanding what exactly is JavaScript Hoisting


Variable declaration and initialization occur in the following sequence:
Declaration –> Initialization/Assignment –> Usage

// Variable lifecycle
let x…

Read more · 5 min read

482 2

Published in Heartbeat · May 31, 2019

Building an App Introduction Slider in React


Native

In this tutorial, we’ll learn the basics of creating an intro slider using React
Native. To do this, we’ll use a React Native module known as react-native-
app-walkthrough, and the result will be a simple and configurable app
introduction slider.

Read more · 4 min read

68 2

Published in Heartbeat · May 20, 2019

Building an Animated Search Bar with React


Native

In this post, we’ll learn to use basic React Native animations while creating a
RN project that has an animated search bar. To do this, we’ll use the react-
native-animatable package.
In most applications, animations are repetitive swipes, slides, bounces, and so
on; react-native-animatable provides preconfigured animated components
that you can use without rewriting commonly-used animations yourself. The
package provides a standard set of easy-to-use animations and declarative
transitions for React Native.
You can see a simulation of what we’re going to create below:

Read more · 6 min read

62

Published in Heartbeat · May 13, 2019

Building a React Native Background Location


Tracking App

In this project, we’ll use the react-native-maps and react-native-

background-geolocation package, a group of React Native map components


for iOS + Android that we’ll use to configure a React Native location tracking
application.
Here, we’ll focus on building the tracking app project for iOS. The library
ships with platform native code that needs to be compiled together with
React Native. This requires you to configure your build tools.

Setting up Google Maps


First, we need to create a new React Native project. Then we can install the
react-native-maps package using NPM or yarn.

Using npm:
npm install react-native-maps — save

Here, we install react-native-maps with…

Read more · 5 min read

187

More From Medium

Coding = thinking digital https://youtu.be/85kXz6L6LDs Run, Build & Deploy What’s The Difference
= thinking web. Gonraf
Stencil and Storybook Between JavaScript And
John Milner
From One Repository ECMAScript
Michael Hoffmann (Mokkapps) Travis Waith-Mair in The Non-
in Nerd For Tech Traditional Developer

Create a Resumable (#6) How to add numbers The Beginner’s Guide to Demystify deployment by
Video Uploader in in an array On ReactJs? Netlify Continuous understanding
Node.js Martin Cho
Deployment from Github environment coupling of
Anam Shah in Technogise
for React Apps code
JJ Ashcraft in HackerNoon.com Akshay Jain

About Write Help Legal

You might also like