How to Integrate Reactjs with Nodejs Tutorial

Integrate Nodejs React Tutorial

How to Integrate Reactjs with Nodejs Tutorial

React is an open-source, front end, JavaScript library for building user interfaces or UI components. React can be used as a base in the development of single-page or mobile. So in the tutorial, I introduce a tutorial: “How to Integrate Reactjs with Nodejs example” with the details steps and running sourcecode.

Related posts:


Video Guide – Integrate Reactjs Nodejs RestAPI

Overview Tutorial – How to integrate Reactjs with Nodejs Example

Diagram Architecture How to Integrate Reactjs and Nodejs RestAPIs Example
Diagram Architecture How to Integrate Reactjs and Nodejs RestAPIs Example

We will build 2 sample projects for the tutorial:
– Frontend: we create a Reactjs project.
– Backend: we create a Nodejs RestAPIs project.

Goal:

React project structure
React project structure
Nodejs Project Structure
Nodejs Project Structure
Integrate successfully between Nodejs RestAPI and Reactjs
Integrate successfully between Nodejs RestAPI and Reactjs

Introduce Reactjs

React is a front-end library developed by Facebook. It is used for handling the view layer for web and mobile apps. ReactJS allows us to create reusable UI components.

Reactjs Component

React is all about components, Components are like functions that return HTML elements. Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function.

Example code:

class Customer extends React.Component {
  render() {
    return <h2>Hi, My name is Jane!</h2>;
  }
}

The component has to include the extends React.Component statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component’s functions.
The component also requires a render() method, this method returns HTML.

Display the Customer component in the “root” element:

ReactDOM.render(, document.getElementById('root'));

Components come in two types, Class components (as above example) and Function components, in this tutorial we will concentrate on Class components.

Example Function Component:

function Customer() {
  return <h2>Hi, I'm Jack!</h2>;
}

React Props

React uses props arguments to pass data into React components via HTML attributes.

Example code:


class Customer extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>My name is {this.props.name}!</h2>;
  }
}

ReactDOM.render(<Customer name="Jack"/>, document.getElementById('root'));

Reactjs State

React components has a built-in state object where you store property values that belongs to the component.
When the state object changes, the component re-renders.

Example:

class Customer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstname: "Jack",
      lastname: "Smith",
      age: "23",
      address: "New York"
    };
  }
  render() {
    return (
      <div>
        <h1>Customer Information</h1>
        <p>
          Firstname: {this.state.firstname}
          Lastname: {this.state.lastname}
          Age: {this.state.age}
		  Address: {this.state.address}
        </p>
      </div>
    );
  }
}

Create Reactjs Project with Create React App

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project directory with Yarn.

yarn create react-app app
Yarn Create Reactjs project
Yarn Create Reactjs project

Project Structure:

React project structure
React project structure

– App.js code:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;

Start Reactjs application: run yarn start in your app directory:

Running Reactjs application in console
Running Reactjs application in console
Reactjs Application starting
Reactjs Application starting

Create Nodejs RestAPI

Before creating a Nodejs project, we need to confirm that the Nodejs and npm had been installed in your computer development by cmd: node -v and npm -v

Checking Nodejs Environment Development
Checking Nodejs Environment Development

If these commandlines are not recognized by command prompt, it means you need to install them by visit the https://nodejs.org/en/ site and download installed package and do the nodejs setup for development later.

Now starting development! Create a folder and named it as Nodejs-React-Integration, go inside the folder, open a cmd and initiate a Nodejs project by cmd npm init.

Install express framework for the project by cmd: npm install express --save

Check the package.json file:

{
  "name": "nodejs-react-integration",
  "version": "1.0.0",
  "description": "Nodejs React Integration",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/loizenai"
  },
  "keywords": [
    "Nodejs",
    "reactjs",
    "integration"
  ],
  "author": "https://loizenai.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Implement a server.js file with a simple GET restapi: /api/customer as below:

const express = require('express');
const app = express();

// Create a Server
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

// respond with "hello world" when a GET request is made to the homepage
app.get('/api/customer', function (req, res) {
  res.json({
    firstname: "Jack",
    lastname: "Smith",
    age: 23,
    address: "374 William S Canning Blvd",
    copyrightby: "https://loizenai.com"
  })
})

Reactjs use Ajax to Fetch data from Nodejs RestAPI

Modify app/src/App.js to use the following code that calls /api/customer and display the response-body in the UI:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {
    isLoading: true,
    groups: []
  };

  async componentDidMount() {
    const response = await fetch('/api/customer');
    const body = await response.json();
    this.setState({ customer: body, isLoading: false });
  }

  render() {
    const {customer, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    return (
      <div className="App">
        <h2>Customer Info</h2>
          Firstname: {customer.firstname}<br/>
          Lastname: {customer.lastname}<br/>
          Age: {customer.age}<br/>
          Address: {customer.address}<br/>
          Copyrightby: <a href="{customer.copyright}">{customer.copyright}</a><br/>
      </div>
    );
  }
}

export default App;

In the function componentDidMount(), we implement a Get Ajax to fetch data from SpringBoot RestAPI then save it in state object of React application.

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json:

"scripts": {...},
"proxy": "http://localhost:8080",

Make sure Nodejs application is running (by cmd: npm start), then re-start Reactjs application by cmd: yarn start in your app directory:

React application in Web browser
React application in Web browser

What is function componentDidMount()?

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases: Mounting, Updating, and Unmounting.

Mounting means putting elements into the DOM with four built-in methods that gets called, in this order, when mounting a component:

  1. the constructor() method is called before anything else, when the component is initiated and it is the natural place to set up the initial state and other initial values.
  2. the getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props.
  3. the render() method is required, and is the method that actually outputs the HTML to the DOM.
  4. the componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.

The render() method is required and will always be called, the others are optional and will be called if you define them.

Read more: React State and Life-cycle

Build Reactjs Application and Integrate with Nodejs project

Build Reactjs application by cmd yarn build

-> result:

Reactjs Build production
Reactjs Build production

After the building process, it creates a build folder as below image:

Check the build production of Reactjs application
Check the build production of Reactjs application

– Copy all files in the new build folder of React project to views folder (we create the views folder) of Nodejs project. Then we modify the server.js file to serve the index.html of Reactjs builded-application as below code:

const express = require('express');
const app = express();

let path = __dirname + '/views/';

app.use(express.static('views'));

// Create a Server
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

// respond with "hello world" when a GET request is made to the homepage
app.get('/api/customer', function (req, res) {
  res.json({
    firstname: "Jack",
    lastname: "Smith",
    age: 23,
    address: "374 William S Canning Blvd",
    copyrightby: "https://loizenai.com"
  })
})

app.get('/', function (req,res) {
  res.sendFile(path + "index.html");
});

Restart Nodejs application and access the URL: http://localhost:8080/:

Integrate successfully between Nodejs RestAPI and Reactjs
Integrate successfully between Nodejs RestAPI and Reactjs

Further Reading

Related posts:


Sourcecode – How to Integrate Reactjs with Nodejs example

Full Sourcecodes: Reactjs + Nodejs

1. Reactjs

How-to-Integrate-Nodejs-Reactjs-Example-Frontend

2. Nodejs RestAPI

Nodejs React Integration

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. Nodejs RestAPI:

SpringBoot RestAPI – Github

Leave a Reply

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