reactjs-chat-tutorial-pubnub

Welcome to chat basics with ChatEngine and React. This is the first of many, but in this part, we’ll cover basic publish-subscribe functionality for sending and receiving chat messages for our React app.

Setup

Before getting started, you’ll have to setup ChatEngine via our ChatEngine Quick Start. This enables you to use your own PubNub application keyset and automagically sets up your account to use ChatEngine. It’ll take a couple minutes at most, then you can come back here and continue on.

Create a ChatEngine/ directory, create a package.json file inside this directory and paste the following in it:

{
  "name": "react-example",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.8.5",
    "react": "15.0.1",
    "react-dom": "15.0.0",
    "create-react-class": "^15.6.3",
    "chat-engine": "^0.8.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "dependencies": {
    "chat-engine": "^0.8.4",
    "create-react-class": "^15.6.3"
  }
}

Run npm install.

When the installation finishes, create a folder called public/ and create a index.html file inside. Add this code to index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ChatEngine React</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Our ChatEngine react app will render inside <div id=”root”>.

JavaScript

In the root of the project, create another folder called src/ and two files inside of it: index.js and index.css. This is where we will add the app’s main functionality.

For the scope of this tutorial you can leave index.css empty but this is where you can add the styling of your app.

We’ll add just a couple of basic properties to center our ChatEngine React app.

* {
    margin: 0px;
    padding: 0px;
}
body {
    width: 500px;
    margin: 30px auto;
    background-color: #fff;
}

Add these lines to the top of index.js inside the src/ folder:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import ChatEngineCore from 'chat-engine'

Add your publish/subscribe keys that you got earlier in the tutorial when you signed up. They’re available in your Admin Dashboard. We’ll also add couple of constants that will help us create our test users.

Lastly, we define our global chat channel:

const now = new Date().getTime();
const username = ['user', now].join('-');
 
const ChatEngine = ChatEngineCore.create({
    publishKey: 'PUB_KEYS_HERE',
    subscribeKey: 'SUB_KEYS_HERE'
}, {
    globalChannel: 'chat-engine-react'
});

Connect with the username we have created:

ChatEngine.connect(username, {
    signedOnTime: now
}, 'auth-key');

Create a Message class that will render our sent messages:

class Message extends React.Component{
    render () {
        return ( <
            div > { this.props.uuid }: { this.props.text } <
            /div>
        );
    }
};

Create a Chat class that will handle the user’s input, send the messages and render our input form:

var createReactClass = require('create-react-class');
var Chat = createReactClass({
 
    // return the initial state of our Chat class
    getInitialState: function() {
        return {
            messages: [],
            chatInput: ''
        };
    },
 
    // update the input field when the user types something
    setChatInput: function(event) {
        this.setState({ chatInput: event.target.value })
    },
 
    // send the message to the other users
    sendChat: function() {
        if (this.state.chatInput) {
            ChatEngine.global.emit('message', {
                text: this.state.chatInput
            });
            this.setState({ chatInput: '' })
        }
    },
 
    // listen for a 'message' event and fire a callback
    componentDidMount: function() {
        ChatEngine.global.on('message', (payload) => {
            let messages = this.state.messages;
            messages.push( <
                Message key={ this.state.messages.length } uuid={ payload.sender.uuid } text={ payload.data.text }
                />
            );
            this.setState({
                messages: messages
            });
        });
    },
 
    // bind the 'Enter' key for sending messages
    _handleKeyPress: function(e) {
        if (e.key === 'Enter') {
            this.sendChat();
        }
    },
 
    // render the input field and send button
    render: function() {
        return ( <
            div >
            <
            div id="chat-output" > { this.state.messages } < /div> <
            input id="chat-input"
            type="text"
            name=""
            value={ this.state.chatInput } onChange={ this.setChatInput } onKeyPress={ this._handleKeyPress }
            /> <
            input type="button"
            onClick={ this.sendChat } value="Send Chat" / >
            <
            /div>
        );
    },
});

And finally render our react elements into the DOM:

ChatEngine.on('$.ready', () => {
    ReactDOM.render( <
        Chat / > ,
        document.getElementById('root')
    );
});

When you’re done, save the file and run the app with npm start. If the app doesn’t open automatically, open localhost:3000 in your browser and you should see the ChatEngine demo up and running.

Next Steps

With that, we have basic messaging for our chat application. With ChatEngine, you can now start adding a ton of powerful plugins, like typing indicators, buddy lists, and emojis, to build out the chat functionality. You can find all the plugins and how to implement them here.

Language:

Use Cases:

Try PubNub Today

Connect up to 100 devices for Free