0% found this document useful (0 votes)
8 views66 pages

Full Stack Module -3 Final

The document provides an overview of the MERN stack, which consists of MongoDB, Express, React, and Node.js, highlighting its components and functionalities. It explains the transition from the MEAN stack to MERN due to the popularity of React as a front-end library and details the characteristics of each component, including their roles in building Single Page Applications (SPAs). Additionally, it introduces the concept of React components, their composition, and a practical example of creating a simple 'Hello World' application.

Uploaded by

akshaya0628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views66 pages

Full Stack Module -3 Final

The document provides an overview of the MERN stack, which consists of MongoDB, Express, React, and Node.js, highlighting its components and functionalities. It explains the transition from the MEAN stack to MERN due to the popularity of React as a front-end library and details the characteristics of each component, including their roles in building Single Page Applications (SPAs). Additionally, it introduces the concept of React components, their composition, and a practical example of creating a simple 'Hello World' application.

Uploaded by

akshaya0628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

GLOBAL ACADEMY OF TECHNOLOGY

DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

VI SEMESTER -2024-25
Module 3: Introduction to MERN

MERN components

Server less Hello world.

React Components: Issue Tracker, React Classes, Composing


Components, Passing Data Using Properties, Passing Data Using Children,
Dynamic Composition.

Text Book 2: Chapter 1, 2, 3


Introduction

What’s MERN?
Any web application is built using multiple technologies. The combinations of
these technologies is called a “stack,”

As web development matured and their interactivity came to the fore, Single Page
Applications (SPAs) became more popular.

An SPA is a web application paradigm that avoids fetching the contents of an


entire web page from the server to display new contents. It instead uses
lightweight calls to the server to get some data or snippets and changes the web
page.
Introduction
The MEAN (MongoDB, Express, AngularJS, Node.js) stack was one of the early
open-source stacks that epitomized this shift toward SPAs and adoption of NoSQL.

AngularJS, a front-end framework based on the Model View Controller (MVC)


design pattern, anchored this stack.

MongoDB, a very popular NoSQL database, was used for persistent data storage.

Node.js, a server-side JavaScript runtime environment, and Express, a web-server


built on Node.js, formed the middle-tier, or the web server.

This stack was arguably the most popular stack for any new web application until a
few years back
Introduction
React, an alternate front-end technology created by Facebook, has been gaining
popularity and offers an alternative to AngularJS. It thus replaces the “A” with an “R” in
MEAN, to give us the MERN Stack.

I said “not exactly” since React is not a full-fledged MVC framework. It is a JavaScript
library for building user interfaces, so in some sense, it’s the View part of the MVC.

GitHub - vasansr/pro-mern-stack-2: Code listing for the book Pro MERN Stack, 2nd Edition
MERN Components

React: Declarative, Component-Based, No Templates, Isomorphic

Node.js: Node.js Modules, Node.js and npm, Node.js is Event Driven

Express

MongoDB : NoSQL, Document-Oriented, Schema-Less, JavaScript Based


MERN Components
React
This is the defining component of the MERN stack. React is an open-source JavaScript
library maintained by Facebook that can be used for creating views rendered in HTML.

Unlike AngularJS, React is not a framework. It is a library. Thus, it does not, by itself,
dictate a framework pattern such as the MVC pattern. You use React to render a view (the
V in MVC)

Not just Facebook itself, but there are many other companies that use React in production
like Airbnb, Atlassian, Bitbucket, Disqus, Walmart, etc.

The 120,000 stars on its GitHub repository is an indication of its popularity.


MERN Components

Declarative

React views are declarative: What this really means you don’t worry about
transitions or mutations in the DOM caused by changes to the view’s state.

Being declarative makes the views consistent, predictable, easier to maintain,


and simpler to understand. It’s someone else’s problem to deal with transitions.
MERN Components
How does this work?
A React component declares how the view looks, given the data. When the data
changes, if you are used to the jQuery way of doing things, you’d typically do some
DOM manipulation.

React takes care of this using its Virtual DOM technology. When things change,
React builds a new virtual DOM based on the new truth (state) and compares it
with the old (before things changed) virtual DOM.

React then computes the differences in the old and the changed Virtual DOM, then
applies these changes to the actual DOM
MERN Components
Component-Based

The fundamental building block of React is a component that maintains its own
state and renders itself.

A component encapsulates the state of data and the view, or how it is rendered.
This makes writing and reasoning about the entire application easier, by splitting
it into components and focusing on one thing at a time.

Components talk to each other by sharing state information in the form of read-
only properties to their child components and by callbacks to their parent
components.
MERN Components
No Templates
Many web application frameworks rely on templates to automate the task of creating
repetitive HTML or DOM elements. The templating language in these frameworks is
something that the developer will have to learn and practice. Not in React.

React uses a full-featured programming language to construct repetitive or conditional DOM


elements. That language is none other than JavaScript.

There is an intermediate language to represent a Virtual DOM, and that is JSX (short for
JavaScript XML), which is very much like HTML. This lets you create nested DOM
elements in a familiar language rather than hand-construct them using JavaScript functions.

Note that JSX is not a programming language; it is a representational markup like HTML. It’s
also very similar to HTML so you don’t have to learn too much.
MERN Components

Isomorphic

React can be run on the server too.

That’s what isomorphic means: the same code can run on the server and the
browser. This allows you to create pages on the server when required
MERN Components
Node.js

Simply put, Node.js is JavaScript outside of a browser.

The creators of Node.js just took Chrome’s V8 JavaScript engine and made it run
independently as a JavaScript runtime. If you are familiar with the Java runtime that runs
Java programs, you can easily relate to the JavaScript runtime: the Node.js runtime runs
JavaScript programs.

Although you may find people who don’t think Node.js is fit for production use, claiming it
was meant for the browser, there are many industry leaders who have chosen Node.js.
Netflix, Uber, and LinkedIn are a few companies that use Node.js in production, and that
should lend credibility as a robust and scalable environment to run the back-end of any
application
MERN Components
Node.js Modules In a browser, you can load multiple JavaScript files, but you need an
HTML page to do all that.

You cannot refer another JavaScript file from one JavaScript file. But for Node.js, there is
no HTML page that starts it all. In the absence of the enclosing HTML page, Node.js uses its
own module system based on CommonJS to put together multiple JavaScript files.

Modules are like libraries. You can include the functionality of another JavaScript file

Node.js ships with a bunch of core modules compiled into the binary. These modules provide
access to the operating system elements such as the file system, networking, input/output,
etc.
MERN Components
Node.js and npm
npm is the default package manager for Node.js. You can use npm to install third-
party libraries (packages) and manage dependencies between them. The npm registry
(www.npmjs.com) is a public repository of all modules published by people for the
purpose of sharing.

Node.js is Event Driven


Node.js has an asynchronous, event driven, non-blocking input/output (I/O) model,
as opposed to using threads to achieve multi-tasking.

Node.js, on the other hand, has no threads


MERN Components
Express

Express is a framework that simplifies the task of writing the server code.

The Express framework lets you define routes, specifications of what to do when an
HTTP request matching a certain pattern arrives. The matching specification is
regular expression (regex) based and is very flexible, like most other web application
frameworks.

Express parses the request URL, headers, and parameters for you. On the response
side, it has, as expected, all functionality required by web applications. This includes
determining response codes, setting cookies, sending custom headers, etc
MERN Components
• you can write Express middleware, custom pieces of code that can be inserted in
any request/response processing path to achieve common functionality such as
logging, authentication, etc.

• Express does not have a template engine built in, but it supports any template
engine of your choice such as pug, mustache, etc.

• But, for an SPA, you will not need to use a server-side template engine. This is
because all dynamic content generation is done on the client, and the web server
only serves static files and data via API calls
MERN Components
MongoDB

MongoDB is the database used in the MERN stack.

It is a NoSQL document-oriented database, with a flexible schema and a JSON-


based query language.

Not only do many modern companies (including Facebook and Google) use
MongoDB in production, but some older established companies such as SAP and
Royal Bank of Scotland have adopted MongoDB
MERN Components
NoSQL

NoSQL stands for “non-relational,” no matter what the acronym expands to. It’s essentially
not a conventional database where you have tables with columns and rows and strict
relationships among them. I find that there are two attributes of NoSQL databases that
differentiate them from the conventional.

• The first is their ability to horizontally scale by distributing the load over multiple servers.
They do this by sacrificing an important (for some) aspect of the traditional databases:
strong consistency.

• The second, and according to me more important, aspect is that NoSQL databases are not
necessarily relational databases. The difference between the representation in the
application (objects) and on disk (rows in tables) is sometimes called impedance
mismatch
MERN Components
Document-Oriented
Compared to relational databases where data is stored in the form of relations, or
tables, MongoDB is a document-oriented database.

The unit of storage (comparable to a row) is a document, or an object, and multiple


documents are stored in collections (comparable to a table). Every document in a
collection has a unique identifier, using which it can be accessed. The identifier is
indexed automatically.

Imagine the storage structure of an invoice, with the customer name, address, etc. and
a list of items (lines) in the invoice. If you had to store this in a relational database, you
would use two tables, say, invoice and invoice_lines, with the lines or items referring
to the invoice via a foreign-key relation.
MERN Components
Schema-Less

Storing an object in a MongoDB database does not have to follow a


prescribed schema. All documents in a collection need not have the same set
of fields.

This means that, especially during early stages of development, you don’t
need to add/rename columns in the schema. You can quickly add fields in your
application code without having to worry about database migration scripts.
MERN Components
JavaScript Based
MongoDB’s language is JavaScript. For relational databases, we had a query language called
SQL. For MongoDB, the query language is based on JSON.

You create, search for, make changes, and delete documents by specifying the operation in a
JSON object. The query language is not English-like (you don’t SELECT or say WHERE), and
therefore much easier to construct programmatically.

Data is also interchanged in JSON format. In fact, the data is natively stored in a variation of
JSON called BSON (where B stands for Binary) in order to efficiently utilize space. When you
retrieve a document from a collection, it is returned as a JSON object.

MongoDB comes with a shell that’s built on top of a JavaScript runtime like Node.js.
Server-Less Hello World
• The React library is available as a JavaScript file that we can include in the HTML
file using the <script> tag.

• It comes in two parts:

 The first is the React core module, the one that is responsible for dealing with
React components, their state manipulation, etc

The second is the ReactDOM module, which deals with converting React
components to a DOM that a browser can understand.
Server-Less Hello World
These two libraries can be found in unpkg, a Content Delivery Network (CDN) that
makes all open-source JavaScript libraries available online.

Let's use the development (as opposed to production) version of the libraries from the
following URLs:

React: https://unpkg.com/react@16/umd/react.development.js

ReactDOM: https://unpkg.com/react-dom@16/umd/react-dom.development.js
Server-Less Hello World
To create the React element, the createElement() function of the React module
needs to be called.

This is quite similar to the JavaScript document.createElement() function,


but has an additional feature that allows nesting of elements.

The function takes up to three arguments and its prototype is as follows.


React.createElement(type, [props], [...children])

Let’s do that and render the Hello World React element:


ReactDOM.render(element, document.getElementById('content'));
<!DOCTYPE HTML>
<html>
<head> <meta charset="utf-8">
<title>Pro MERN Stack</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="contents"></div>
<script> const element = React.createElement('div', {title: 'Outer div'},
React.createElement('h1', null, 'Hello World!') );
ReactDOM.render(element, document.getElementById('content'));
</script>
</body>
</html>
Chapter 3 : React Components
Issue Tracker

GitHub Issues or Jira

These applications help you create a bunch of issues or bugs, assign them to
people, and track their statuses.

CRUD applications

only deal with a single object or record,


Issue Tracker
Here’s the requirement list for the Issue Tracker application, a simplified or toned-
down version of GitHub Issues or Jira:

• The user should be able to view a list of issues, with an ability to filter the list by
various parameters.

• The user should be able to add new issues, by supplying the initial values of the
issue’s fields.

• The user should be able to edit and update an issue by changing its field values.

• The user should be able delete an issue.


Issue Tracker
An issue should have following attributes:

• A title that summarizes the issue (freeform long text)


• An owner to whom the issue is assigned (freeform short text)
• A status indicator (a list of possible status values)
• Creation date (a date, automatically assigned)
• Effort required to address the issue (number of days, a number)
• Estimated completion date or due date (a date, optional)
React Classes
React classes are used to create real components .

These classes can then be reused within other components, handle events, and
so much more

React classes are created by extending React.Component, the base class from
which all custom classes must be derived.

Within the class definition, at the minimum, a render() method is needed.


This method is what React calls when it needs to display the component in the
UI.
React Classes
• Lifecycle methods

• render() is one that must be present, otherwise the component will have no
screen presence

• The render() function is supposed to return an element (which can be


either a native HTML element such as a <div> or an instance of another
React component)
...
class HelloWorld extends React.Component { ... }
...
React Classes
• within this class, a render() method is needed, which should return an element.
We’ll use the same JSX <div> with the message as the returned element.

• construction to within the render() function so that it remains encapsulated within


the scope where it is needed rather than polluting the global namespace.

• In essence, the JSX element is now returned from the render() method of the
component class called Hello World. The brackets around the JSX representation
of the Hello World element are not necessary, but it is a convention that is
normally used to make the code more readable, especially when the JSX spans
multiple lines.
Composing Components
Component composition is one of the most powerful features of React.

This way, the UI can be split into smaller independent pieces so that each
piece can be coded and reasoned in isolation, making it easier to build and
understand a complex UI.

Using components rather than building the UI in a monolithic fashion also


encourages reuse

A component takes inputs (called properties) and its output is the rendered
UI of the component
Composing Components
Here are a few things to remember when composing components:

• Larger components should be split into fine-grained components when there is a


logical separation possible between the fine-grained components
.
• When there is an opportunity for reuse, components can be built which take in
different inputs from different callers.

• React’s philosophy prefers component composition in preference to inheritance.

• In general, remember to keep coupling between components to a minimum


Composing Components
Let’s design the main page of the application to show a list of issues, with an ability
to filter the issues and create a new issue. The structure and hierarchy of the user
interface is shown in Figure 3-1.
Composing Components
• Let’s define three placeholder classes—IssueFilter, IssueTable, and IssueAdd—
with just a placeholder text within a <div> in each.

• To put these together, let’s add a class called IssueList.

• Now let’s add a render() method. Within IssueList method,

• Let’s use a Fragment component like this in the IssueList’s render() method

• let’s instantiate the IssueList class, which we will place under the contents div.
Lab Program -5
Build a React application to track issues. Display a list of issues (use
static data). Each issue should have a title, description, and status
(e.g., Open/Closed). Render the list using a functional component.
Ubuntu + Node.js Setup
Install Windows Subsystem for Linux (WSL) on Windows

In window search Bar-Turn on off window feature


Enable->Windows-Subsystem-Linux & Virtual machine
platform

Next,
• Restart the computer when prompted.
• Again in search bar -Microsoft store-type ubuntu
• Select ubuntu app-click on get.
• Then install->takes a will to install.
• Open click once done it ask for user name & password.
• Ready to work ,better to check installed properly by
checking some UNIX commands.
April, 2025 Department of ISE, GAT, Bangalore, India 43
Ubuntu + Node.js Setup

Install NVM on Ubuntu:


1.sudo apt-get update
Enter your password when prompted, and wait for the process to complete. This command updates the local
package index to reflect the latest changes in the repository.

2.sudo apt install curl


The above command installs the curl package, and it is utilized in downloading NVM and other resources.

3. curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh


| bash
The above command downloads the NVM installation script directly from the official GitHub
repository and pipes it into the bash shell to run it. Make sure that you update v0.39.1 with the current version at
the time of your installation.
April, 2025 Department of ISE, GAT, Bangalore, India 44
Ubuntu + Node.js Setup

Verify NVM Installation on Ubuntu: nvm –version

Install Node.js Using NVM:

nvm install –lts


nvm ls //list all versions

nvm install 18 //idle version


nvm use 18

nvm –version

April, 2025 Department of ISE, GAT, Bangalore, India 45


Set up the React frontend issue-tracker/
├── node_modules/ ← project dependencies
Create the React app (auto-managed)
├── public/
│ ├── favicon.ico
│ ├── index.html ← main HTML file
Open your terminal and run: │ ├── logo192.png
npx create-react-app issue-tracker │ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
it will create a folder called issue-tracker/ with this default ├── src/
file and folder structure: │ ├── App.css ← styles for App component
│ ├── App.js ← main React component
│ ├── App.test.js ← basic test file
cd issue-tracker │ ├── index.css ← global styles
│ ├── index.js ← entry point for React app
│ ├── logo.svg
│ ├── reportWebVitals.js ← optional performance
reporting
│ └── setupTests.js ← test setup
├── .gitignore ← ignores node_modules, logs,
etc.
├── package.json ← project metadata & scripts
├── README.md ← basic project instructions
Department of ISE, GAT, Bangalore,├──
India package-lock.json ← exact dependency 46 versions
April, 2025
Set up the React frontend
What you’ll mostly edit:
src/App.js → your main app logic
src/App.css → styles for App.js
src/index.js → React entry point
public/index.html → HTML wrapper

Add the Issue Tracker component

• Inside src/, create a file called IssueTracker.jsx.


• Paste the code in next slide inside this file:
-Logic of the program
April, 2025 Department of ISE, GAT, Bangalore, India 47
import React from "react";
import "./issuelist.css";
const issues = [
{ id: 1, title: "Login page error", description: "500 error", status: "Open" },
{ id: 2, title: "Broken image", description: "Dashboard image not loading", status: "Closed" },
{ id: 3, title: "Profile update fails", description: "Profile save fails", status: "Open" },
];
const IssueList = () => (
<div className="container">
<h1 className="heading">Issue Tracker</h1>
{issues.map((issue) => (
<div key={issue.id} className="issue-card">
<div className="issue-header">
<h2 className="issue-title">{issue.title}</h2>
<span className="issue-status">{issue.status}</span>
</div>
<p>{issue.description}</p>
</div>
))}
</div>
);
exportApril, 2025
default IssueList; Department of ISE, GAT, Bangalore, India 48
Set up the React frontend
Use CSS classes and a CSS file
Inside src/ ,Add to IssueList.css by creating new file
.issue-card{
.container{ .issue-title{
margin-bottom:1rem;
max-width:640px; font-size:1.25rem;
padding:1rem;
margin:0 auto; font-weight:600;
border:1px solid #ccc;
padding:16px; }
border-radius:4px;
} .issue-status{
background-color:#f9f9f9
font-size:0.9rem;
.heading{ }
padding:2px 6px;
font-size:1.875rem; .issue-header{
border-radius:4px;
font-weight:bold; display:flex;
background-
margin-bottom:1.5rem; justify-content:space-between;
color:#eee;
text-align:center; align-items:center;
}
} April, 2025
margin-bottom:0.5rem;
Department of ISE, GAT, Bangalore, India 49
}
How to connect it
Render the component in App.js
Place IssueList.js and IssueList.css in the src/ folder.
Import and use IssueList in your App.js:
In src/App.js, replace the content with:
import IssueList from "./issuetracker";

function App() {
return <IssueList />;
}
export default App;
April, 2025 Department of ISE, GAT, Bangalore, India 50
Check index.js->Make sure src/index.js looks like:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root =
ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
April, 2025 Department of ISE, GAT, Bangalore, India 51
Check index.html

Also, check that your public/index.html has this line:


…….
<div id="root"></div>
…..

April, 2025 Department of ISE, GAT, Bangalore, India 52


• Check if the dev server is running correctly
In the terminal, after you run
npm start

confirm you see: Compiled successfully!

You can now view issue-tracker in the browser.


Local: http://localhost:3000 // automatically opens in Microsoft
edge
Note:
Stop the server → Ctrl + C
Clear cache → rm -rf node_modules/.cache
Restart → npm start

If you only see “webpack compiled” but no


“You can now view...” message, something is stuck.

If Error then,
 Confirm App.js renders something
 Confirm IssueList.js exports properly
 Confirm index.js attaches to #root
 Restart dev server
 Test with simple text
April, 2025 Department of ISE, GAT, Bangalore, India 54
Passing Data Using Properties

• Props (short for "properties") are read-only attributes used to pass data
from one component to another, typically from a parent component to a
child component.

• They help make components reusable and dynamic.


Parent Component defines and passes props:
function Parent() {
const handleClick = () => alert("Button clicked!");

return (
<div>
<Child name="Alice" age={25} onClick={handleClick} />
</div>
); }
Child Component receives and uses props:
function Child({ name, age, onClick }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<button onClick={onClick}>Click Me</button>
</div>
); }
Passing Data Using Properties
Passing Different Types of Data via Props

Strings: <Child text="Hello" />


Numbers: <Child count={5} />
Booleans: <Child isActive={true} />
Arrays/Objects: <Child data={[1, 2, 3]} />
Functions: <Child onClick={handleClick} />
JSX/Components: <Child footer={<Footer />} />
Passing Data Using Properties
• let’s create a component called IssueRow, and then use this multiple times within
IssueTable, passing in different data to show different issues, like this:
let’s pass the issue’s title (as a string), its ID (as a
number), and the row style (as an object) from
IssueTable to IssueRow.

Within the IssueRow class, we’ll use these passed-in


properties to display the ID and title and set the style of
the row, by accessing these properties through
this.props
class IssueTable extends React.Component {
render() {
const rowStyle = {border: "1px solid silver", padding: 4};
return (
<table style={{borderCollapse: "collapse"}}>
<thead>
<tr>
<th style={rowStyle}>ID</th>
<th style={rowStyle}>Title</th>
</tr>
</thead>
<tbody>
<IssueRow rowStyle={rowStyle} issue_id={1}
issue_title="Error in console when clicking Add" />
<IssueRow rowStyle={rowStyle} issue_id={2}
issue_title="Missing bottom border on panel" />
</tbody>
</table> ); }}
Passing Data Using Children

• There is another way to pass data to other components, using the contents of the
HTML-like node of the component.

• In the child component, this can be accessed using a special field of this.props
called this. props.children.

• we nested a<h1> element inside a <div>. When the components are converted
to HTML elements, the elements nest in the same order. React components can
act like the and take in nested elements.
Dynamic Composition
• In this section, we’ll replace our hard-coded set of IssueRow components with a
programmatically generated set of components from an array of issues.

const issues = [
{ id: 1, status: New', owner: 'Ravan', effort: 5, created: new Date('2018-
08-15'), due: undefined, title: 'Error in console when clicking Add', },

{ id: 2, status: 'Assigned', owner: 'Eddie', effort: 14, created: new


Date('2018-08-16'), due: new Date('2018-08-30'), title: 'Missing
bottom border on panel', },
];
App.jsx: IssueTable Class with IssueRows Dynamically Generated and Modified Header

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy