Author avatar

Raphael Alampay

Create a Simple React.js Component with Backed Node.js API

Raphael Alampay

  • Oct 10, 2020
  • 7 Min read
  • 152 Views
  • Oct 10, 2020
  • 7 Min read
  • 152 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Summary

Becoming a full-stack web developer can involve a steep learning curve since, at the very least, you'll have to learn how to code in three domains: 1) the persistence layer, 2) the application layer, which provides the logic, and 3) the view layer for rendering interfaces that the user can interact with. In most cases, each of these layers will be implemented in a different programming language, thus increasing the amount of material you'll have to learn. However, with Javascript, you can easily use a single programming language that encompasses all three layers making the learning experience a little bit more manageable.

In this guide, we'll take a look at how to build a simple backend server using Javascript Node.js as the application layer and React.js as the view layer that interacts with the backend to simulate the full stack experience.

Setting up the Server

The server application you'll be creating will be a mock API endpoint that returns JSON data. Start off by creating a Javascript file called app.js with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var http = require('http');

var hostname  = '127.0.0.1';
var port      = 3000;

var app = http.createServer(function(req, res) {
            res.setHeader('Content-Type', 'application/json');

            res.end(
              JSON.stringify({
                firstName: "John",
                lastName: "Doe"
              })
            );
          });

app.listen(port, hostname);
javascript

Using plain Javascript and Node.js, you can easily create a server application server that acts as an endpoint. The line res.setHeader('Content-Type', 'application/json') forces the response to return data as JSON. The function res.end() accepts a string version of a JSON object that contains a firstName and a lastName, which will be the payload of this endpoint. The server application is started by running the line app.listen(port, hostname), whose parameters are set to the localhost and port number 3000 of the host machine.

Running the Server

Issue the following command in your terminal to start running the server:

1
$ node app.js
bash

Using your browser, visit the URL http://localhost:3000 and you should see the JSON object being returned with the following form:

1
2
3
4
{
  "firstName": "John",
  "lastName": "Doe"
}
json

Once you've verified that your mock endpoint is working, perform the same action, but this time programmatically using a React.js frontend component.

Creating the React.js Frontend

Start off by creating a React component called PersonComponent with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';
import $ from 'jquery';

export default class PersonComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      firstName: "",
      lastName: ""
    }
  }

  render() {
    return (
      <div>
        <h1>{this.state.firstName} {this.state.LastName}</h1>
      </div>
    );
  }
}
javascript

This vanilla component will simply display the firstName and lastName state values. Initially, these values are set as an empty string.

Next, create a method that fetches data from your backend API, whose endpoint is http://localhost:3000. Create the following fetch method in your component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fetch() {
  var context = this;

  $.ajax({
    url: 'http://localhost:3000',
    method: 'GET',
    success: function(response) {
      context.setState({
        firstName: response.firstName,
        lastName: response.lastName
      });
    }
  });
}
javascript

You first create a reference context whose value is this, referring to the instance of your component. This will be used later on in the logic of the success function after the code has made a successful call to the API backend. context will then invoke setState and update the React.js component's state values coming from response, which in turn is the JSON object that was returned by the API.

The last thing to do is invoke fetch automatically when the component is first mounted. To do so, override the React.js component method componentDidMount() with the following logic:

1
2
3
componentDidMount() {
  this.fetch();
}
javascript

All that will do is call fetch once the component has been successfully mounted. In turn, fetch will interact with the API, update the state, and force a re-render of the view with the updated values, thus completing the cycle.

Overall Code

The final code will look like the following:

Server Application

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var http = require('http');

var hostname  = '127.0.0.1';
var port      = 3000;

var app = http.createServer(function(req, res) {
            res.setHeader('Content-Type', 'application/json');

            res.end(
              JSON.stringify({
                firstName: "John",
                lastName: "Doe"
              })
            );
          });

app.listen(port, hostname);
javascript

ReactJS Frontend

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React from 'react';
import $ from 'jquery';

export default class PersonComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      firstName: "",
      lastName: ""
    }
  }

  componentDidMount() {
    this.fetch();
  }

  fetch() {
    var context = this;

    $.ajax({
      url: 'http://localhost:3000',
      method: 'GET',
      success: function(response) {
        context.setState({
          firstName: response.firstName,
          lastName: response.lastName
        });
      }
    });
  }

  render() {
    return (
      <div>
        <h1>{this.state.firstName} {this.state.LastName}</h1>
      </div>
    );
  }
}
javascript

Conclusion

In this guide, you've seen how to use a single programming language to implement both the backend and frontend components of your app. This shortens the learning curve since you only have to focus on learning one programming language instead of a variety of languages that deal with different layers of your system. In most cases, this can prove to be a much more agile approach to building applications since you can devote your time to going deeper with Javascript and understanding its more advanced intricacies while still being able to contribute to all parts of your tech stack. Adding a persistence layer will be easier as well since you just have to look for an abstraction layer, also written in Javascript, that provides API calls for the underlying database.

For any questions or concerns, or if you simply want to chat about programming in general, hit me up @happyalampay!

2