Building A React Native Chat App - Part One - Basic Messaging - PubNub - by Krissanawat Kaewsanmuang - Medium
Building A React Native Chat App - Part One - Basic Messaging - PubNub - by Krissanawat Kaewsanmuang - Medium
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:
Set Up
In this step, we’ll create a React Native project using the following command:
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.
# OR
Grab the example code from the GitHub readme file and paste it into the
App.js file.
Replace the code in the default class with the following piece of code:
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.
In this step, we’ll install the PubNub SDK. You can install the package using
the following commands.
Using NPM:
Using Yarn:
Once the installation is done, you need to import the PubNubReact module
from the pubnub-react package as shown in the code:
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' }); });
}
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.
Next, we need to configure the chat channel using PubNub as set it up along
with Gifted Chat. Follow these simple steps:
onSend(messages = []) {
this.pubnub.publish({ message: messages, channel: "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.
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.
this.id = this.randomid();
Lastly, add the state and function to the GiftedChat HTML, as shown in the
code below.
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.
268 1
Image Source
71 1
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
// Variable lifecycle
let x…
482 2
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.
68 2
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:
62
Using npm:
npm install react-native-maps — save
187
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