Hacktoberfest – Added user is typing… feature using React and SocketIO

This blog post covers my 5th pull request of Hacktoberfest 2018!!!! For a few days I wasn’t sure if I would be able to reach the 5 PR goal.  I got super busy with another project, which I may put a blog post up about that project sometime. I was able to work hard on Hacktoberfest the past couple day’s and now I am done all 5 PR’s!!!

Back to the topic of this post I’ll put a summary blog post of Hacktoberfest soon.

I add the feature that show’s when a user is typing which was requested in issue #1 of the node chat project.  Here is the link to the pull request.

In order to accomplish this task I used two events on the server side. ‘typing’ and ‘stop typing’.

Server Code
socket.on('typing', function(){
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  socket.on('stop typing', function(){
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

For the client code I put the two event listener’s inside the componentDidMount().

The event listener for ‘typing’ add’s the user name to a state variable ‘userIsTyping’ which is an array of the user names that are typing.

The event listener for ‘stop typing’ removes the user name from ‘userIsTyping’.

Client Code
componentDidMount() {
  this.state.socket.on('typing', (user) => {
      if(this.state.username!==user.username){
        if(!this.state.userIsTyping.find(function(users){
              return users==user.username;
           })) {
          this.setState({userIsTyping: [...this.state.userIsTyping, user.username] });
        }
      } 
  });

  this.state.socket.on('stop typing', (user) => {
    if(this.state.username!==user.username){
       this.setState({userIsTyping: this.state.userIsTyping.filter(function(users) {
           returnusers!==user.username;
         })});
       }});
    }
  }
}

The function below is used to retrieve the content of the input field. It will emit ‘typing’ if there is anything inside the input field and it will emit ‘stop typing’ when there is nothing inside the input field.

setChatInput(event) {
  if(event.target.value !== ""){
    this.state.socket.emit('typing', this.state.username);
  } else if(event.target.value === ""){
    this.state.socket.emit('stop typing', this.state.username);
  }
  this.setState({ chatInput:event.target.value });
}

The end result looks like this:

Hacktoberfest – Bug Fixes and Styling in NodeChat app.

For my 3rd and 4th pull request of Hacktoberfest, I didn’t work on much new technology, like in my previous pull request’s. Instead I thought I would fix a bug that was added during the move from a jQuery site to a React site. And I added some styling to the messages on the NodeChat app.

PR #3 

In the original jQuery site the original creator designed it to display a greeting message when a user logs in. From testing the original site, the greeting message only displayed the first time someone logged in. This is were the React app had a bug, it would always display the greeting message when you enter the chat.

In order to fix this bug I needed to have the idea of a previous user inside the chat page component. I was able to do this by creating a Boolean inside the login page and sending that over to the chat page through props. This allowed my to conditionally show the greeting message.

 

PR #4

Since the chat app can handle more then just 2 people at a time, I wanted to show who is sending each message. I was already receiving the username of the sender so it wasn’t technically that hard to get the username to display. Their was a bug in receiving the username but it was quick to fix.

The more involved part of this PR was probably all the CSS required to make the messages look nice.

Here’s a picture of the end result:

 

 

Hacktoberfest – Adding sound and images to a React app

Hey everyone,

It seems like allot of people like to over complicate adding sound and images in React.  They will often make a whole separate class to control their sound or image files. Which definitely has its place, if your sound or images needs bunch of options then definitely make a class to control it. But if all you want to do is play a sound or add a image to your app, I think its simpler to add it in directly inside the class it relates to.

Note:  I also learned that React doesn’t like when you refer to something by its path inside the code. You have to use a import statement in order to include a file into your react app. In the code below you will see me do this.

 

Playing Sound in React:

Below is how I figured out how to play sound from my react app in just a few statements.

import mp3_file from './yourFileName.mp3';

playSound(){
   this.Sound.play();
}

<audio src={mp3_file} ref={Sound => { this.Sound = Sound; }}/>
Adding a Image in React:

Below is a simple way of adding a image to your React app.

import myImg from './yourFileName.png';

<img src="{myImg}" />

Hacktoberfest Week Two – React and Push.js

In this week of Hacktoberfest, I added push notifications to the Node Chat project in my most recent Pull request. I used the Push.js library in order to accomplish this task. Well learning how to do this, I din’t find much documentation on using Push.js with React so I put together a small tutorial for today’s blog.

Integrating Push.js with React

Natively, there is currently no solution to use Push.js with React. In order to use Push.js with react you have to use it as an external libraries. Below is how I added Push.js to React as an external library.

First step:

Include the script file in the main “index.html” file for your app.

I used a CDN to do this:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/push.js/1.0.7/push.min.js"></script>

Second step:

Import Push.js into your file.

Put the following line at the top of the .js file you want to use Push.js in.

import * as Push from "push.js";

After importing Push.js you can now create push notifications inside your react app.

Here’s an example of how to create a notification in a react component.

notify(){
 Push.create("Hello world!", {
     body: "Thanks for reading my Blog!",
     timeout: 5000,
     onClick: function () {
         window.focus();
         this.close();
     }
 });
}

 

Hacktoberfest Week One

In my first week of Hacktoberfest I started off without any particular project in mind. I had a few ideas of what I wanted to work on, so I started by searching GitHub for a project. I was looking for something using JavaScript or C++.

After searching for a while I came across a application called NodeChat. In Issue #11 for the NodeChat project the owner asked for someone to move the public site over to React. Having used React, Node.js and Socket.IO I asked in the issue if I could do this.  After, that I started my work on the React app to replace the JQuery version that was previously used in the project.

Making a chat app using React

I started off with some project designing. I needed to figure out how I wanted to organize the react app. Also, I had to go through the existing JQuery file to get a better understanding of what the project is doing.

I decided on the below structure for the app.

    • App
      • This component is the core of the app were the Login Page is called and is currently were all the css and assets are located.
    • LoginPage
      • This component handles new and previous user login’s.  And handles displaying the login page or the chat page.
    • ChatPage
      • This compenent handles all the functionality of the chat.

Currently the flow of the app is as follows the app page displays the Login page. The login page creates a new user or uses a previous user then the Login page decides when to display the Chat page.

A update I think I will do at some point would be to make it so the App page receives props back form the Login page. That would instruct the App page when to display the Chat page. I think this would be a bit cleaner code.

There is still a bunch of stuff that need’s to be finished but at the moment the app is working on a basic level. I am hoping to get most of the bugs fixed as soon as I can.

I think this will be a good project for me over Hacktoberfest and probably after.

Here’s the link to my first PR of Hacktoberfest .

Below is the 2 class definitions for Login Page and Chat Page and I added a small comment about each function. Full Code available here.

class LoginPage extends Component {
    constructor(props) {}
    // Checks if user pressed enter key to submit there message.
    enterKeyPress(e) {}
    // Used to manage the State of the input field on the Login Page.
    setUsernameInput(event) {}
    // Calls checkIfPreviousUser()
    componentDidMount() {}
    // Sets the username 
    setUsername() {}
    // Checks current user is a previous user or calls setUsername() if not.
    checkIfPreviousUser() { }
    // Tell the server that we've had a user join
    userJoin() {}
    // Holds the content's of the Login Page
    displayLogin() {}
    // Render Login Page if not loged in or Chat page if Logged in
    render() {}
}

class ChatPage extends Component {
    constructor(props) {}
    // Calls greetUser() and Lisen's for New Chat messages.
    componentDidMount() {}
    // Displays Greeting message.
    greetUser() {}
    // Checks if user pressed enter key to submit there message.
    enterKeyPress(e) {}
    // Used to manage the State of the input field on the chat app.
    setChatInput(event) {}
    // Send's the message to the server.
    sendMessage() {}
    // Recieve's the chat messages from the server.
    addChatMessage(data) {}
    // Used to handle images(not tested).
    parseMessageText(inputString) {}
    // Used to handle images(not tested).
    imageFile(filetype) {}
    // Used to handle images(not tested).
    getFileType(inputString) {}
    // Used to handle images(not tested)..
    imageLink(inputString) {}
    // Used automatically scroll the page.
    scrollToBottom() {}
    // Render page content.
    render() {}
}