Impact of React in MERN Stack Development

Introduction

In my previous article, I explained the fundamentals of React, including setting up the environment with Node.js and npm installation. The article guides readers through creating a React app and running it.

  1. Node.js- Introduction, Features, Installation Guide, and Benefits.
  2. How to Create a MongoDB Atlas Account?
  3. MVC Architecture With Node.js CRUD Application [Node.js-Express-MongoDB]
  4. View in React.js within the MVC Architecture

In my previous articles, I covered the following topics.

  1. Introduction to MVC Architecture
  2. Creating a Node.js Application and Setting Up Environment Variables
  3. Establishing the MongoDB Connection and Connecting the App
  4. Implementing MVC Architecture for Node.js Applications
  5. Creating CRUD Operations using Node.
  6. Fundamentals of React, creating a React app and running it. Additionally, it introduces the basic process of connecting an API to the front end using Axios.

Introduction of the MERN Stack

Now, I'm going to talk about the MERN stack. The MERN stack is a powerful combination of four key technologies: MongoDB, Express.js, React.js, and Node.js. It empowers developers to build modern web applications that are scalable, efficient, and easy to maintain. In this section, we will explore the architecture and benefits of the MERN stack.

MongoDB

Database: MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON).

Express.js

Backend Framework: Express.js is a backend web application framework for Node.js, designed to simplify the process of building robust and scalable web applications and APIs.

React.js

Frontend Library: React is a JavaScript library developed by Facebook for building user interfaces. It allows developers to create reusable UI components that update in response to changes in the application state. It is commonly used for building interactive and dynamic single-page applications (SPAs).

Node.js

Runtime Environment: Node.js is a JavaScript runtime built on the V8 JavaScript engine. It allows developers to run JavaScript code on the server side, enabling the development of server-side applications.

MERN Stack Srchitecture

Picture 1. MERN stack Architecture

In my previous articles, I covered MEN stack development. You can refer to the link here.

MongoDB Database: How to Create a MongoDB Atlas Account?

Express.js and Node.js

Backend Framework and Runtime Environment: MVC Architecture With Node.js CRUD Application [MongoDB-Express-Node.js]

Above the link, I explain what MVC Architecture is and how it works in a real environment, and I also cover MEN stack development. I explain the student CRUD operation scenario and how to apply MEN stack development in the MVC pattern. I covered the Model and Controller in MVC Architecture in the article above. Now, I'm going to explain the 'VIEW' in MVC Architecture in this article.

What is the VIEW in MVC?

In the context of the Model-View-Controller (MVC) architectural pattern, the "View" represents the user interface (UI) or presentation layer of an application. The View is responsible for displaying the data to the user and capturing user input. It receives information from the Model (which represents the application's data and business logic) and presents it in a way that is suitable for the user to interact with.

Controller

Picture 2. The View is responsible for displaying the data to the user and capturing user input.

View in MVC: Key Characteristics and Responsibilities

  • Presentation Logic: Displays data from the Model to users.
  • User Interface Elements: Contains UI components for user interaction.
  • Data Display: Renders and updates data dynamically.
  • No Business Logic: Avoids business logic, and focuses on presentation.
  • Observer Pattern: Listens for Model changes to update itself.
  • Independence: Modular and independent of business logic.

The View is essentially responsible for the visual representation and user interaction aspects of an application within the MVC architecture.

Now I’m continuing MERN stack development with MVC.

React.js

A JavaScript library for building user interfaces. Developed by Facebook, React.js allows developers to build reusable UI components that efficiently update and render when the underlying data changes. React.js is particularly well-suited for building single-page applications (SPAs).

Impact of react in MERN stack development

  1. Efficient UI Development: React's declarative and component-based approach simplifies UI development.
  2. Virtual DOM for Performance: Virtual DOM optimizes rendering, enhancing application performance.
  3. State Management: React facilitates easy state management for dynamic content and user interactions.
  4. Reusable Components: Component-based architecture promotes code reusability and modularity.
  5. Rich Ecosystem: Active community and third-party libraries enhance development capabilities.
  6. SPA Development: React is well-suited for building responsive single-page applications (SPAs).
  7. Easy Backend Integration: Seamless integration with Node.js backend for full-stack development.
  8. Developer Productivity: JSX and component structure improve code readability and developer productivity.

Now I’m continuing with my last article. View in React.js within the MVC Architecture

Share the app.js here.

import logo from './logo.svg';
import './App.css';
import axios from "axios";

function App() {
  const loadStudentData = async () => {
    const res = await axios.get("http://localhost:5000/api/student");
    console.log("<<<Get Student Data>>>>", res.data)
  };
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p> My Project :</p> <button onClick={loadStudentData}>Click to retrieve student data. 
                   </button>     
      </header>
    </div>
  );
}

export default App;

Local host

Picture 3. successfully fetching the data to the console.

Integrated with API and GUI using Axios. For the API, we need to install the Cross-Origin Resource Sharing (CORS) npm package.

I can demonstrate what happens with an HTTP request call without CORS.

Handling CORS Policy Error

Runtime error

Picture 4. Referrer-Policy: strict-origin-when-cross-origin.

Referrer policy

Picture 5. Access to XMLHttpRequest at 'http://localhost:5000/api/student' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORS

Picture 6. Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What is the Cors?

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict webpages from making requests to a different domain than the one that served the original webpage. This is a crucial security mechanism to prevent potentially harmful cross-origin HTTP requests.

When you are building a Node.js application that serves resources (like APIs), and your front end is hosted on a different domain, you might encounter CORS issues. The browser will, by default, block requests from the front end to the backend if they are from different origins.

With CORS

Picture 7. Might encounter CORS issues

To enable cross-origin requests and avoid CORS issues in a Node.js application, you can use the Cors middleware. Here's why you might want to install and use Cors.

Install the Cross-Origin Resource Sharing (CORS) npm package.

Add this two-line code in node.js API index.js.

const cors = require('cors');


// Enable CORS for all routes
 app.use(cors({ origin: 'http://localhost:3000' }));

Again we will run the react: npm start.

We got the console output here. You can see the image in the response data. It is an array object to display the data in the UI/ View.

View

Picture 8. It is an array with 9 elements, and each element is an object.

Summary

The article explores the impact of React in MERN stack development, emphasizing its role in building modern web applications. It covers the MVC architecture, introduces the MERN stack, and discusses the key technologies (MongoDB, Express.js, React.js, Node.js). The author provides insights into React's efficiency, state management, and component-based architecture.

A code snippet demonstrates fetching data using Axios in a React component, and the article addresses CORS issues in Node.js applications. The summary concludes with the importance of enabling cross-origin requests for seamless integration in MERN stack development.

This content is tailored for individuals interested in self-learning. Feel free to stay connected with me for more updates.


Orfium Sri Lanka
Globally based Software Developing & Data Processing Company