3 Introduction to MERN
Module 3
CS380
What Is MERN?
2
A stack of technologies used to build web
applications.
Popularized by the LAMP stack (Linux, Apache,
MySQL, PHP).
Evolution of Web Applications
Shift to Single Page Applications (SPAs):
Avoids refreshing the entire page for new
content.
Uses lightweight server calls for data updates.
SPAs are more interactive and efficient compared
to traditional web pages.
CS380
MEAN Stack (Predecessor of
3
MERN)
MongoDB: NoSQL database for data
storage.
Express: Web server built on [Link].
AngularJS: Front-end framework (MVC
pattern).
[Link]: Server-side JavaScript runtime
environment.
Popular stack for developing SPAs.
CS380
MERN Stack (Modern
4
Alternative)
MongoDB: Database.
Express: Web server framework.
React: JavaScript library for building
user interfaces (replacing AngularJS).
[Link]: Server-side JavaScript.
CS380
Difference Between AngularJS
5
& React
AngularJS: Full-fledged MVC
framework.
React: A JavaScript library focused on
the View part of MVC.
Why MERN?
Provides a complete framework for building
modern SPAs.
Requires additional tools and libraries to
complement React for building full
CS380
applications.
Example of a Simple MERN
Application:
6
Frontend: React (UI Components).
Backend: [Link] + Express (API and
Routing).
Database: MongoDB (Data Storage).
CS380
MERN Components
7
Overview
MERN Stack consists of React, Express,
[Link], and MongoDB.
React is the main component anchoring the
stack.
React
What is React?
An open-source JavaScript library
maintained by Facebook.
Used for creating user interfaces rendered in
CS380
HTML.
Focuses on the View (V) part of the MVC
Characteristics of React
8
Not a Framework: Unlike AngularJS,
React is a library, not a full-fledged
framework.
Component-Based Architecture:
Breaks the UI into reusable components.
Declarative: Simplifies building
interactive UIs by managing state and
rendering views based on data changes.
CS380
Declarative
9
React views are declarative, meaning
developers don't manage the changes in
the DOM manually.
React updates the view efficiently using
a Virtual DOM — an in-memory
representation of the actual DOM.
It computes differences between old and
new views and applies only necessary
changes to the real DOM.
Ensures consistent, predictable, and
CS380
maintainable code.
Component-Based
10
React is built using components, which
are reusable, self-contained building
blocks of a UI.
Each component manages its own state
and renders itself.
Components can be combined to form
complex user interfaces.
Communication between components is
done via props (read-only properties)
and callbacks.
CS380
Encourages a modular structure making
No Templates
11
Unlike other frameworks that use
templating languages, React uses
JavaScript itself for rendering views.
Uses JSX (JavaScript XML), a syntax
similar to HTML, to define UI
components.
JSX makes it easier to write and visualize
the structure of the components.
Pure JavaScript can be used instead of
JSX if preferred.
CS380
Isomorphic (Universal
12
Rendering)
React can be rendered on the server as
well as the browser.
Improves SEO (Search Engine
Optimization) by rendering pages on the
server.
Uses [Link] on the server to execute
JavaScript code for rendering React
components.
CS380
✅ [Link]
13
Definition: [Link] is JavaScript running
outside of a browser.
How it Works: Built on Chrome’s V8
JavaScript engine to run JavaScript
programs independently.
Comparison: Similar to how the Java
runtime runs Java programs, the
[Link] runtime runs JavaScript
programs.
Purpose: Allows building server-side
CS380
and networking applications using
💡 Example Use Cases:
14
Building web servers and APIs.
Creating real-time applications (e.g., web
applications, chat apps, games).
CS380
✅ [Link] Modules
15
🔍 What are Modules?
Modules: Like libraries that contain reusable code.
In [Link], modules allow you to split code into separate
files for better organization.
[Link] uses CommonJS module system to manage
multiple JavaScript files.
🔍 How Modules Work:
In a browser, JavaScript files are loaded via an HTML page.
In [Link], there’s no HTML page; instead, modules are
loaded using require().
Example:
const fs = require('fs'); // Loading the 'fs' module for file
CS380
operations
🔍 Types of Modules:
16
Core Modules:
Pre-installed with [Link] (e.g., fs, http,
path).
Provides access to OS elements (file
system, networking, etc.).
User-defined Modules:
Files created by developers to organize
their code better.
Third-party Modules:
Open-source libraries installed via npm
CS380 (Node Package Manager).
✅ [Link] and npm
17
🔍 What is npm?
Default package manager for [Link].
Used to install and manage third-party libraries
(packages).
Accesses the npm registry ([Link]), a
public repository of modules.
🔍 Why npm is Important:
Manages dependencies between packages.
Allows installation of client-side libraries like
React and jQuery.
Supports conflict resolution: Multiple versions
CS380
of a module can coexist.
✅ [Link] Is Event Driven
18
🔍 What Does Event Driven Mean?
[Link] uses an asynchronous, event-
driven model.
No threads like in other languages; instead,
it uses callbacks.
Handles tasks like file reading, networking,
etc., without blocking the main process.
🔍 How It Works:
Uses an Event Loop (a queue of tasks to
process).
CS380 When an event completes (e.g., file read),
Example of Callback:
19
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data)
=> {
if (err) throw err;
[Link](data);
});
[Link]("Reading file...");
Output:
Reading file...
(File content appears here)
CS380
Non-blocking: Code continues to run even while waiting
🔍 Benefits:
20
Fast and Efficient: No waiting; tasks
are processed as they complete.
No Threads Needed: Avoids
complexity of managing threads, locks,
and semaphores.
CS380
✅ Express
21
🔍 What is Express?
A framework for [Link] that simplifies
building web servers.
Makes it easier to handle HTTP requests
and responses.
Provides a structure for creating routes,
middleware, and APIs.
🔍 Key Features:
Routing System:
Define URLs and their corresponding
CS380 handling functions.
Middleware:
Custom functions inserted into the request/response
process.
22
Used for tasks like logging, authentication, etc.
Response Handling:
Easily set response codes, headers, cookies, etc..
[Link](200).send('OK’);
🔍 Template Engine Support:
In MERN stack, React handles page generation on the
client-side.
🔍 Why Use Express?
Simplifies creating servers.
Clean structure for routing and middleware handling.
CS380
Popular for building APIs and backend services.
✅ MongoDB
23
🔍 What is MongoDB?
Database used in the MERN stack.
NoSQL, document-oriented database.
Stores data as JSON-like documents
instead of rows and columns.
CS380
🔍 NoSQL Features:
24
Non-Relational Database:
No tables and columns like SQL databases.
Stores data in documents (JSON format).
Horizontal Scalability:
Can distribute data across multiple servers.
Uses techniques like scaling.
Schema Flexibility:
Allows storing documents with different
structures in the same collection.
No predefined schema is required.
CS380
🔍 Advantages of MongoDB:
25
Easier Data Representation:
Data is stored in the same format as it is
used in the application (Objects/JSON).
No need for complex Object-Relational
Mapping (ORM).
High Performance:
Optimized for read/write operations.
Can handle large amounts of unstructured
data.
Scalability:
CS380
Perfect for applications that require quick
✅ MongoDB: Schema-Less & JavaScript
Based
26
🔍 Schema-Less Database:
No Fixed Structure:
Documents in a collection can have different
fields.
Allows easy modification without database
migration.
Flexible Development:
You can quickly add or rename fields without
hassle.
Ideal for rapid prototyping and evolving
applications.
🔍 JavaScript Based Database:
CS380
✅ Tools and Libraries
27
🔍 React-Router:
Purpose:
Manages URLs and history in single-page
applications (SPAs).
Helps transition between views without
reloading the entire page.
Features:
Supports the Back button functionality.
Associates code with URLs like server-side
routing.
Why Use It:
CS380
Makes navigation smooth and efficient in
✅ Webpack
28
🔍 What is Webpack?
Purpose:
Tool for modularizing and bundling JavaScript code.
Converts various files (JavaScript, CSS, images) into
a single bundle for the browser.
Why Use Webpack?
Easy to use, compared to other tools like Browserify.
Doesn’t require additional tools like gulp or grunt for
build management.
Uses in React Apps:
Bundles client-side code for easy delivery to the
browser.
CS380
✅ Why MERN? (Overview)
29
Single Language Everywhere:
JavaScript for client-side, server-side, and
database scripts (MongoDB).
Easier context switching and code sharing
between client & server.
JSON Everywhere:
Data represented as JSON in database,
application server, client, and API calls.
No ORM or serialization required,
simplifying data handling.
CS380
✅ Why MERN? (Performance &
Flexibility)
30
[Link] Performance:
Event-driven architecture & non-blocking
I/O for high performance.
Scales well with increased traffic, reducing
troubleshooting.
npm Ecosystem:
Access to a vast library of packages for
easy integration.
Fastest and most convenient package
manager.
React is a Library, Not a Framework:
CS380
✅ Server-Less Hello World (Using React - Without
Installation)
31
Creating a simple Hello World application
with React directly in an HTML file
without any server or installations.
📌 1. Purpose
To quickly set up a React app without using
[Link], npm, or any server.
Helps understand the basic environment for
working with React.
CS380
📌 2. Code ([Link])
32
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>Pro MERN Stack</title>
<script
src="[Link]
<script src="[Link]
[Link]"></script>
<script
src="[Link]
</head>
CS380
33
<body>
<div id="contents"></div> <!-- React component will be
rendered here -->
<script type="text/babel">
var contentNode =
[Link]('contents');
var component = <h1>Hello World!</h1>; // Simple
JSX component
[Link](component, contentNode); //
Rendering component to the browser
</script>
</body>
</html>
CS380
📌 3. Steps to Run
34
Save the code above as [Link].
Open the file in your browser (Double-
click or Right-click -> Open with
Browser).
CS380
Content Delivery Network
35
(CDN)
1. What is CDN?
A Content Delivery Network (CDN) is
a network of geographically distributed
servers.
It helps deliver web content (images,
videos, CSS, JavaScript) efficiently.
CDN reduces latency by serving content
from the nearest server to the user.
CS380
Importing React
36
• React Library: Provides core React
functionalities for building components.
• ReactDOM Library: Allows rendering of
React components to the DOM (HTML
elements).
• Babel Library: Transforms JSX (React
syntax) into plain JavaScript that the
browser can understand.
CS380
React Code
37
var contentNode =
[Link]('contents');
Grabs the <div> element where the React
component will be displayed.
var component = <h1>Hello World!</h1>;
Defines a simple JSX component that
displays the text "Hello World!".
[Link](component,
contentNode);
Renders the JSX component inside the
<div> element with id="contents".
CS380
📌 Why Use Babel?
38
1. Compatibility:
1. Many browsers do not support modern
JavaScript features (ES6+).
2. Babel converts modern code to older
versions that all browsers can understand.
2. Using JSX:
1. React uses JSX (JavaScript XML), which
is not directly understood by browsers.
2. Babel converts JSX to plain JavaScript.
CS380
39
CS380
Separate HTML and JSX
40
Step 1: Modify [Link] (Separate HTML and JSX)
Save this as [Link]:
<html>
<head>
<!-- React and ReactDOM from CDN -->
<script
src="[Link]
</head>
<body>
<div id="contents"></div> <!-- React component will be rendered here
-->
<!-- Load external JSX file -->
<script type="text/babel" src="/static/[Link]"></script>
</body>
</html>
CS380
Step 2: Create [Link] (JSX
41
Code)
Save this as [Link]:
var contentNode =
[Link]('contents'); //
Get the div
// Simple JSX Component
var component = <h1>Hello, World! This
is a React Component.</h1>;
// Render the component to the browser
CS380
Steps to Install [Link]
42
1. Install [Link] (Includes npm)
Download [Link] from the official
website: [Link]
Choose the LTS (Long-Term Support)
version for stability.
Run the installer and follow the installation
steps.
2. Verify Installation
node -v
CS380
NVM (Node Version
43
Manager)
NVM (Node Version Manager) is a tool
that allows you to install, manage, and
switch between multiple [Link]
versions on your system.
nvm install node
nvm install 4.5
CS380
Creating a Project Using
44
npm
1️⃣Initialize a [Link] project
mkdir my-project
cd my-project
npm init -y # Creates [Link] with
default values
2️⃣Install dependencies
npm install express # Installs [Link]
3️⃣Run the project
node [Link]
CS380
Node Package Execute
45
🔹 npx (Node Package Execute) is a tool that
comes with npm (v5.2+).
🔹 It allows you to run npm packages without
installing them globally.
Creating a Project Using npx
1️⃣Create a React app (example)
npx create-react-app my-app
cd my-app
npm start
CS380
React Components
46
React components are reusable,
independent pieces of UI.
There are 2 types of React components
Functional Components (Preferred)
Class Components
CS380
1️⃣Functional Components
47
(Preferred)
Simple JavaScript functions that return
JSX.
Uses React Hooks for state and lifecycle
features.
Lightweight and faster than class
components.
Example: Functional Component
import React from "react";
function Hello() {
CS380
48
//import React from "react";
function Hello() {
return <h1>Hello, ise!</h1>;
}
// Render the component
const root = [Link]([Link]("root"));
[Link](<Hello />);
//
[Link]([Link]("root")).render(<Hello
/>);
// export default Hello;
✅ import React → It is an object that contains various utilities required for building
React applications
✅ from "react" → This tells JavaScript where to get React from (the installed React
package).
CS380
✅ Advantages:
49
Easier to read and maintain.
Better performance.
Uses useState and useEffect instead of
lifecycle methods.
CS380
2️⃣Class Components (Older
50
Method)
Uses ES6 classes and extends
[Link].
Has lifecycle methods like
componentDidMount,
componentDidUpdate.
Requires [Link] and [Link] for
managing state.
CS380
example
51
//import React, { Component } from "react";
class Hello extends [Link] {
render() {
return <h1>Hello, RNS!</h1>;
}
}
// Render the component
const root = [Link](document.
getElementById("root"));
[Link](<Hello />);
//export default Hello;
CS380
52
✅ 1. import React from "react";
Imports the React library, which is needed to use JSX
(the syntax for writing components).
✅ 2. import { Component } from "react";
Component is a built-in class in React.
Instead of writing [Link], we can directly
use Component.
Makes code shorter and easier to read.
CS380
❌ Disadvantages:
53
More complex syntax.
Requires this keyword.
Slower than functional components.
💡 Which One to Use?
✅ Use Functional Components for new
projects.
❌ Avoid Class Components unless
working with old code.
CS380
Composing Components
54
What is Component Composition?
Combining multiple smaller components to
build a larger UI.
Helps in reusability and better organization.
Why Use Component Composition?
Encapsulation: Each component handles its
own logic.
Reusability: Components can be used
multiple times in different places.
Maintainability: Easier to debug and update
CS380 specific parts of the UI.
Composing Components
55
CS380
Composing Components
56
CS380
Example: Composing
57
Components
Designing a main page with three
sections:
IssueFilter: Filters the displayed issues.
IssueTable: Displays the list of issues.
IssueAdd: Form to add new issues.
CS380
Issue tracker
58
CS380
Passing Data
59
What is Props in React?
✅ Props (short for "properties") are used
to pass data from a parent component to
a child component in React.
✅ They are read-only, meaning a child
component cannot modify them.
✅ Props help reuse components by
making them dynamic.
CS380
Prop using class component
60
CS380
Key Modifications:
61
✅ Used a single Hello component instead
of multiple components.
✅ Passed messages as props (message
attribute).
✅ More maintainable – new messages can
be added easily.
CS380
Prop using functional component
62
CS380
Passing Multiple Props
63
CS380
Property Validation in
64
React?
Property validation (or prop validation)
ensures that React components receive
props of the correct type and structure.
It helps developers avoid bugs by
warning when props are missing or
incorrect.
We are passing a message prop from the
parent component. Now let’s validate
that:
message must be a string
CS380
message is required
Example
65
import PropTypes from 'prop-types';
function Hello(props) {
return <h1>{[Link]}</h1>;
}
// ✅ Property Validation
[Link] = {
message: [Link]
};
CS380
Full Example
66
CS380
Benefits
67
✅ Benefits of This Validation
• Catches bugs early
• Helps during development with clear
error messages
• Makes your component usage self-
documented
CS380
Passing Data Using Children
68
If we want to pass dynamic JSX content
(like text, HTML, or even other
components) inside the component tags,
not as a named prop like message.
Using children allows your component
to:
Be more flexible
Accept nested content
Act like a wrapper or layout
CS380
✅ Updated Hello Component (Class-
Based):
69
class Hello extends [Link] {
render() {
return
<h1>{[Link]}</h1>; // 👈
using children instead of message
}
}
CS380
Example using class
70
component
CS380
Example using functional
71
component
CS380
🎯 Why Use children?
72
More flexible than named props like
message.
Supports HTML, JSX, and nested
elements inside.
Great for wrapping or layout components
like <Card>, <Panel>, etc.
CS380
✅ Dynamic Components
73
Here, you create
one reusable
component and
pass different
data to it using
props or
[Link].
This makes it
flexible.
CS380
74
CS380
🧠 What's New Here?
75
[Link] and [Link] are used to
customize each card’s heading and label
[Link] still handles the main
dynamic content
CS380