The complete code for this section: GitHub

This article is part 3 of a series on building chat applications using ReactJS and Go. You can find part 2 – back-end implementation here

The Header component

Let’s start by creating a very simple Header component. We need to create a new directory called components/ under the frontend/ SRC/directory and add a Header/ directory to it, which will hold all files of the Header component.

- src/
- - components/
- - - Header/
- - - - Header.jsx
- - - - index.js
- - - - Header.scss
Copy the code

Note – whenever we create a new component, we will create a new directory in the components/ directory where we will create these three files (.jsx,.js, *.scss).

Header.jsx

We need to implement the function component in the header. JSX file. This will be used to render the title of the site:

import React from "react";
import "./Header.scss";

const Header = (a)= > (
  <div className="header">
    <h2>Realtime Chat App</h2>
  </div>
);

export default Header;
Copy the code

Header.scss

Next, we need to add some styles. Since the ReactJS project does not have the ability to process SCSS files, we first need to install Node-sass by running the following command in the frontend/ directory:

$ yarn add node-sass
Copy the code

Once installed, we can add styles:

.header { background-color: #15223b; width: 100%; margin: 0; padding: 10px; color: white; h2 { margin: 0; padding: 0; }}Copy the code

index.js

Finally, we export the Header component so that other components can import it and display it in their own render() function:

import Header from "./header.jsx";

export default Header;
Copy the code

Update the App. Js

Now that the Header component is created, we need to import it into app.js and display it by adding it to our Render () function, as follows:

// App.js
// Import components from relative paths
import Header from './components/Header/Header';
// ...
render() {
  return (
    <div className="App">
      <Header />
      <button onClick={this.send}>Hit</button>
    </div>
  );
}
Copy the code

After saving this file, our front-end application needs to be recompiled, and you can see the Header component successfully displayed at the top of the browser page.

Congratulations – you have successfully created your first React component!

History chat history component

We’ve already built and rendered a very simple component, so let’s build a slightly more complex one.

In this section, we will create a history chat component that displays all the messages we receive from the WebSocket service.

We will create a new folder in the components/ directory called ChatHistory/. Again, we need to create three files for this component.

ChatHistory.jsx

Let’s start with the ChatHistory. JSX file. It’s a little more complicated than before, because we’ll be building a Class component instead of the Function component of our Header component above.

Note – we can define class components using ES6 calSS. If you want to learn more about this, you are advised to check out the official documentation: Features and Class Components

In this component, you’ll notice that there is a render() function. The Render () function returns a JSX to display this particular component.

This component will receive a set of chat messages from the app.js function via props and display them from the top down in a list.

import React, { Component } from "react";
import "./ChatHistory.scss";

class ChatHistory extends Component {
  render() {
    const messages = this.props.chatHistory.map((msg, index) = > (
      <p key={index}>{msg.data}</p>
    ));

    return (
      <div className="ChatHistory">
        <h2>Chat History</h2>
        {messages}
      </div>); }}export default ChatHistory;
Copy the code

ChatHistory.scss

In ChatHistory. SCSS we add a small style for the ChatHistory component, simply changing the background color and padding and margins:

.ChatHistory { background-color: #f7f7f7; margin: 0; padding: 20px; h2 { margin: 0; padding: 0; }}Copy the code

Index.js

Finally, we need to export the new component, just as we did with the Header component, so that it can be imported and displayed in app.js:

import ChatHistory from "./ChatHistory.jsx";

export default ChatHistory;
Copy the code

Update app.js and API /index.js

Now that we’ve added the ChatHistory component, we need to actually provide some messages.

In the previous part of this series, we set up two-way communication that echoes whatever was sent to it, so that whenever we click the Send message button in the application, we receive a new message.

Update the API /index.js file and the connect() function to call back when it receives a new message from a WebSocket connection:

let connect = cb= > {
  console.log("connecting");

  socket.onopen = (a)= > {
    console.log("Successfully Connected");
  };

  socket.onmessage = msg= > {
    console.log(msg);
    cb(msg);
  };

  socket.onclose = event= > {
    console.log("Socket Closed Connection: ", event);
  };

  socket.onerror = error= > {
    console.log("Socket Error: ", error);
  };
};
Copy the code

Therefore, we add a cb parameter to the function. This cb callback is called on line 10 every time we receive a message.

When we are done with these changes, we can add this callback function via app.js and use setState to update the status when we get a new message.

We’ll move the constructor function connect() to be called in the componentDidMount() function, which is automatically called as part of the component lifecycle.

// App.js
  componentDidMount() {
    connect((msg) = > {
      console.log("New Message")
      this.setState(prevState= > ({
        chatHistory: [...this.state.chatHistory, msg]
      }))
      console.log(this.state);
    });
  }
Copy the code

Then update app.js’s render() function and show the ChatHistory component:

render() {
  return (
    <div className="App">
      <Header />
      <ChatHistory chatHistory={this.state.chatHistory} />
      <button onClick={this.send}>Hit</button>
    </div>
  );
}
Copy the code

When we compile and run the front end and back end projects, we can see that whenever the send message button on the front end is clicked, it continues to send messages through the WebSocket connection to the back end, which then passes them back to the front end and finally displays them successfully in the ChatHistory component!

conclusion

We successfully improved the front-end application and treated it as a chat application. In the next part of this series, we will focus on the following:

  • Improved front end: Added a new sending message component to allow us to send custom messages
  • Improved backend: Handles communication between multiple clients and across clients.

Next section: Part 4 – Handling multiple clients


Original text: tutorialedge.net/projects/ch…

Author: Elliot Forbes

This article is originally compiled by GCTT and published by Go Chinese