View in React.js within the MVC Architecture

In my last article, I explained MVC architecture, demonstrated how to create a Node.js application, connect to the database, and implement CRUD operations using node js. Now, I will explain how to work with the View in the MVC pattern.

  1. Node.js- Introduction, Features, Installation Guide, and Benefits.
  2. How to Create a MongoDB Atlas Account?
  3. Node.js RESTful API Project with Express, MongoDB, and Postman.
  4. MVC Architecture With Node.js CRUD Application [Node.js-Express-MongoDB]

In my previous article, I covered the following topics:

  1. Introduction to MVC Architecture
  2. Creating a Node.js Application
  3. Setting Up Environment Variables
  4. Establishing the MongoDB Connection and Connecting the App
  5. Implementing MVC Architecture for Node.js Applications
  6. Creating CRUD Operations using Node.

Introduction of View

In the Model-View-Controller (MVC) architectural pattern, the "View" represents the user interface (UI) or presentation layer of an application. The primary responsibility of the View is to display the data provided by the Model in a way that is understandable to the user and to relay user input back to the Controller for processing.

Here are the key characteristics and responsibilities of the View in MVC:

  • Presentation Logic: The View is responsible for presenting the data to the user in a human-readable format. It defines how the information from the Model should be displayed. This involves formatting, organizing, and representing the data in a visually appealing manner.
  • User Interface Elements: The View contains various UI elements such as buttons, text fields, images, and other components that users interact with. These elements are often defined using markup languages (e.g., HTML in web development).
  • Notification of User Input: When a user interacts with the UI, the View captures these events and forwards them to the Controller for processing. The Controller then determines how to respond to these events, possibly by updating the Model or changing the state of the View.

Picture 1: MVC in VIEW.

Key Programming Languages Driving Dynamic View Development

As for popular languages used in View development in MVC frameworks, it depends on the framework and the technology stack being used. 

Sure, here's a list of popular programming languages commonly used in view development:

  • JavaScript: Used with frameworks like React, Angular, and Vue.js for frontend development, enabling dynamic and interactive views in web applications.
  • HTML/CSS: While not programming languages, these are essential for creating the structure and styling of web pages and interfaces.
  • TypeScript: A superset of JavaScript that adds static typing, making code more robust, especially when building larger applications.
  • Python: Often used in combination with frameworks like Django or Flask for backend development, which impacts the data displayed in views.
  • Java/Kotlin: Android development often involves these languages, used to create the views in mobile applications.
  • Swift: Used for iOS development, allowing the creation of visually appealing and functional views in iPhone and iPad applications.
  • Ruby: Employed with frameworks like Ruby on Rails, which includes view templating systems for web applications.
  • PHP: Commonly used in conjunction with server-side technologies to generate dynamic views on web pages.

These languages are often paired with specific frameworks or tools to facilitate view development within different platforms or for specific purposes. Each has its strengths and is chosen based on factors such as project requirements, ease of development, and ecosystem support.

In this article, I'm going to explain how to create view pages using React.js.

What is the React js?

React.js is a JavaScript library for building user interfaces, particularly for building single-page applications where you want a smooth, efficient, and dynamic user experience. It was developed by Facebook and is maintained by both Facebook and a community of individual developers.

Now, I’m going to explain how to create a react.js application step by step.

Building Your First React.js Application: A Step-by-Step Guide


Step 1. Set Up Your Development Environment

Node.js and npm/yarn: Ensure Node.js is installed on your system. npm or yarn will be necessary for managing packages.

First, it is necessary to install Node.js. I have written an article detailing how to set up Node.js; you can refer to this article where I explain the process step by step: 

'Set Up The Node Environment and Run a Simple Node Server Project.

Understanding NPM and Yarn: Package Managers in Software Development

npm (Node Package Manager):

npm is the default package manager for Node.js, which is a JavaScript runtime built on Chrome's V8 JavaScript engine. It is used to install, manage, and share packages of code, typically for server-side JavaScript applications. npm is bundled with Node.js, so when you install Node.js, npm is automatically installed as well.

yarn:

Yarn is an alternative package manager for JavaScript. It was created by Facebook in collaboration with other developers and organizations.

Yarn aims to be more efficient, reliable, and deterministic in package installations compared to npm. Yarn also supports offline installations, meaning it can install packages without an internet connection if the dependencies are already cached.

In my article, I will guide you through using Node.js along with npm. I will cover the installation process for both Node.js and npm. 

To verify the installation and confirm whether the correct version was installed,

Enter the following command to Check the node version.

Node --version or Node -v

Check the npm version, and run this command:

npm --version or npm -v

npm --version or npm -v

Picture 2. Node version: 20.10.0 and npm version: 10.2.3

Step 2. Create a React Application

I. Create React App: 

Use create-react-app, a tool that sets up a new React project with all the necessary dependencies and files.

npx create-react-app my-react-app

npx:

npx is a package runner tool that comes with npm (Node Package Manager). It is used to execute packages, especially for those that are not globally installed. In this case, it's used to run the create-react-app package without the need to install it globally.

Now I’m going to create my project.

Example project name: studentViewReact

npx create-react-app

Picture 3. In your case, the project name "studentViewReact" includes capital letters ("V" and "R"), and npm is informing you that this is not allowed.

project name: student_view_react

Create react app

Picture 4. Successfully! Created my react app student_view_react.

i. Navigate to Your App Directory: 

Move into the newly created app directory.

D:\Project\StudentMVC_node_React> cd student_view_react

ii. Open the project folder in the vs code 

D:\Project\StudentMVC_node_React\student_view_react> code .

Step 3. Development and Building

01 Start the Development Server: npm start

This command will start the development server, usually on http://localhost:3000.

npm start

Picture 5. npm start

Picture 6. Compiled successfully! You can now view student_view_react in the browser.

Connecting a React Frontend to a Node.js Backend API

In my previous article, I covered MVC Architecture with a Node.js CRUD application in a real-time project. We utilized Postman to visualize the response data Please check the article link for more details.

Now I’m using the same project details and continue HTTP GET method. router.get("/student", getAllStudents);

Check the postman here. GET method and using this route. http://localhost:5000/api/student.

HTTP GET method

Picture 07: Here, we can see the get all student results.

Now, we retrieve the response in the frontend ('VIEW') using React.js  in our project 'student_view_react.

First, we’ll install axios …

What is axios?

Axios is a widely-used JavaScript library that simplifies the task of making HTTP requests in web browsers or Node.js. It streamlines the process of sending asynchronous requests and managing their responses. With its straightforward and intuitive API, Axios is commonly chosen for tasks like fetching data, interacting with APIs, and handling HTTP requests in both frontend and backend applications. Its compatibility with promises and the async/await syntax contributes to its widespread adoption.

Sending asynchronous HTTP requests

Picture 08:  Sending asynchronous HTTP requests and managing their responses.

Install axios

I've attached the Axios npm package. If you need more details, please go through the link.

npm i axios

After installing Axios, check the package.json file to confirm whether Axios has been added to the dependencies or not.

App.js page

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;

Jest I simply create a button click and call the loadStudentData function.

<button onClick={loadData}>Click to retrieve student data.</button>

loadStudentData as a async arrow function (=>).

  const loadStudentData= async () => {
    const res = await axios.get("http://localhost:5000/api/student");
    console.log("<<<Get Student Data>>>>", res.data)
  };

Function, it uses Axios, specifically the axios.get() method, to send an HTTP GET request to "http://localhost:5000/api/student" to fetch data from that API endpoint. 

After successfully fetching the data, it logs "<<<Get Student Data>>>>" along with res.data to the console.

Picture 09:  Successfully fetching data to the console.

Summary

This article discusses the 'View' aspect within the MVC architecture and then transitions to a new topic: React.js. It covers 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. Additionally, it introduces the basic process of connecting an API to the frontend using Axios. This content is tailored for individuals interested in self-learning. Feel free to stay connected with me for more updates.


Adelanka (PVT) LTD
Globally based Software Developing & Data Processing Company