Discussion

MAKING REACT REALTIME WITH WEBSOCKETS

Every chat application requires real time functionality. This amongst other benefits allows interaction between users in different location(s). A chat application like this can be built to function on diverse platforms, be it mobile or web applications.

In this tutorial, I will be showing you how to build a chat application using React and Pusher. This is a very simple application and it comes with functionality which will be showing some of the rich features of Pusher and how you can easily combine it with a modern library like React.

Pusher is a platform that allows developers to easily build an application with realtime features as quickly as possible. Pusher specialises in building realtime and scalable infrastructures for developers and is packaged with powerful features like client events, queryable API, Pub/Sub messaging and others.

We will explore Pusher as we proceed in this tutorial and leverage on the DOM manipulation, event driven and data-binding ability of React.

A basic knowledge of JavaScript and React will be of advantage so as to effectively participate in this tutorial.

Getting Started

For a hitch-free flow of procedures in this tutorial, we will begin by setting up the required credentials with Pusher. If you don’t have an account, kindly create one . Once you are done, go ahead and create a new app from your dashboard. Don’t forget to take note of your app_id, key, secret and cluster as you will be required to use them later in this tutorial.

Create React-app

To quickly scaffold a React app, we will make use of the create``-react-app tool. This gives us easy access to the CLI tool that will be used to start building our chat application.

It is important that you have Node and npm installed on your machine. Quickly follow this link to complete that, if you don’t have it already. To verify if you have Node and npm installed, open up the terminal and run the command below:

    npm -v 
    node -v

The version for each one will be displayed, if they are installed. The latest versions are fine.

Installation

Now, install create-react-app and also scaffold a new React app with the following commands:

    npm install -g create-react-app

    create-react-app react-pusher

Once all the necessary files are installed, change directory into react-``pusher and start the application with:

    npm start

Node Server

Node.js using the Express web framework will be used as our server application. The server application, amongst other functions, will provide endpoints to send messages for our chat app so as to ensure interaction between users. There are number of dependencies required for the application server, so let’s install them immediately:

    npm install --save axios body-parser cors express pusher pusher-js

To configure the entry point of the application, create a file called server.js and paste the code below into it:

const Pusher = require('pusher');
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');

    const app = express();

    app.use(cors());
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
    const pusher = new Pusher({
      appId: 'APP_ID',
      key: 'APP_KEY',
      secret: 'APP_SECRET',
      cluster: 'APP_CLUSTER',
      encrypted: true
    });
    app.set('PORT', process.env.PORT || 5000);

    app.post('/message', (req, res) => {
      const payload = req.body;
      pusher.trigger('chat', 'message', payload);
      res.send(payload)
    });

    app.listen(app.get('PORT'), () => 
      console.log('Listening at ' + app.get('PORT')))

Building Components

To define a good application structure and fully see our chat app in action, lets create some components. In React, components can either be stateful or stateless depending on the functionality that it was created for. The common patter is to have state for container components only and pass those states to UI components as props.

Create components from the terminal with:

    touch ChatList.js ChatBox.js

and lastly their respective stylesheet:

    touch ChatList.css ChatBox.css

Each of the components’ logic need to be created. Lets do that now

ChatBox.js

This component contains the input field for accepting the users message and also displays a welcome message showing the username passed in from the parent component. Furthermore, handleTextChange is also passed from the parent component. This component is exported and configured like:

import React from "react";
    import './ChatBox.css';
    export default ({ text, username, handleTextChange }) => (
      <div>
        <div className="row">
        <div className="col-xs-12">
          <div className="chat">
            <div className="col-xs-5 col-xs-offset-3">
              <input
                type="text"
                value={text}
                placeholder="chat here..."
                className="form-control"
                onChange={handleTextChange}
                onKeyDown={handleTextChange}
              />
            </div>
            <div className="clearfix"></div>
          </div>
        </div>
        <h4 className="greetings">Hello, {username}</h4>
      </div>
    </div>
    );


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *