Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

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

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.

Oct 10, 2020 • 7 Minute Read

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:

      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);
    

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:

      $ node app.js
    

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

      {
  "firstName": "John",
  "lastName": "Doe"
}
    

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:

      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>
    );
  }
}
    

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 https://localhost:3000. Create the following fetch method in your component:

      fetch() {
  var context = this;

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

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:

      componentDidMount() {
  this.fetch();
}
    

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

      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);
    

ReactJS Frontend

      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>
    );
  }
}
    

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!

Raphael Alampay

Raphael A.

Raphael Alampay is the co-founder of Cloudband Solutions Co., a software development and consultancy company that caters to custom based software for SME around the globe. Using time and tested technology such as Java, Ruby on Rails, Python, PostgreSQL and Linux, he has a passion for creating applications that solve real world problems making businesses more efficient and innovative at the same time. His craft in software is largely based on the philosophy of "kaizen" which means continuous improvement; that any piece of software is meant to be continuously improved over time. Aside from software development, Raphael also teaches computer science in universities and corporate entities largely in the field of programming and machine learning. He currently holds a master's degree in Computer Science and is working on his PhD in Computer Science as well. If not programming or teaching, Raphael enjoys playing the piano and guitar in his spare time.

More about this author