PubNub React SDK 3.0.2
Chat SDK
If you want to create a React chat app, you can use our Chat SDK, which relies on the JavaScript SDK, is written in TypeScript, and offers a set of chat-specific methods to manage users, channels, messages, typing indicators, quotes, mentions, threads, and many more.
PubNub's React framework allows you to use PubNub's JavaScript SDK features within a React application.
React SDK deprecation
The older PubNub React SDK v.1.3.1 has been deprecated.
Requirements
To use the PubNub React framework, you need:
- React 16.8 or above
- PubNub Javascript SDK.
PubNub account
Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.
When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.
Download the React wrapper
PubNub's React framework isn't a complete SDK. Rather, it's a wrapper around PubNub's JavaScript SDK that exposes the JS functionality to React components. This means that in order to work with PubNub's React framework, you need to download and add the JavaScript SDK to your React app.
-
First, set up your React project. For a quick single-page app, create-react-app is a good starting point:
npx create-react-app react-sample-chat -
Add the PubNub JavaScript SDK and React framework packages to your project:
cd react-sample-chat
npm install --save pubnub pubnub-react
Configure PubNub
In the IDE of your choice, open your React app in a new project and add the following to the source/App.js file. This is the minimum configuration you need to send and receive messages with PubNub.
Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.
import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';
const pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: 'myUniqueUUID'
});
function App() {
return (
<PubNubProvider client={pubnub}>
<Chat />
</PubNubProvider>
show all 17 linesFor more information, refer to the Configuration section of the SDK documentation.
Add event listeners
Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.
Copy the code below to configure your app such that when it receives an event of type message, it adds the message to the responsible component's state. The component then renders based on its current state and displays the message.
function Chat() {
const pubnub = usePubNub();
const [channels] = useState(['awesome-channel']);
const [messages, addMessage] = useState([]);
const [message, setMessage] = useState('');
const handleMessage = event => {
const message = event.message;
if (typeof message === 'string' || message.hasOwnProperty('text')) {
const text = message.text || message;
addMessage(messages => [...messages, text]);
}
};
useEffect(() => {
const listenerParams = { message: handleMessage }
pubnub.addListener(listenerParams);
show all 21 linesFor more information, refer to the Listeners section of the SDK documentation.
Publish and subscribe
To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.
In this app, publishing a message is triggered when you click the Send Message button.
To subscribe, you send a subscribe() call.
const sendMessage = message => {
if (message) {
pubnub
.publish({ channel: channels[0], message })
.then(() => setMessage(''));
}
};
useEffect(() => {
const listenerParams = { message: handleMessage }
pubnub.addListener(listenerParams);
pubnub.subscribe({ channels });
return () => {
pubnub.unsubscribe({ channels })
pubnub.removeListener(listenerParams)
show all 17 linesFor more information, refer to the Publish and Subscribe section of the SDK documentation, and to Sending Messages.
Putting it all together
Your App.js file should now look similar to the following. Note that the following code also defines some UI for demonstration:
import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';
const pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: 'myUniqueUUID'
});
function App() {
return (
<PubNubProvider client={pubnub}>
<Chat />
</PubNubProvider>
show all 147 linesNow, run your app to see if you did everything correctly. In you project directory, run the npm start command. You should now see the chat UI in your browser. Try sending a message!
Congratulations! You've just subscribed to a channel and sent your first message.
Walkthrough
Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:
- configures a PubNub connection
- passes the PubNub connection config to the
PubNubProvidercomponent (context) which allows you to use PubNub's functionality inside of other components of that context - adds the
messageevent listener - subscribes to a channel
- publishes a message