UNIT V Notes
UNIT V Notes
UNIT V versa.
REACT • This setup also involved templates, which are predefined structures or formats used to render the
user interface. Soon, this got pretty hairy as the application became more and more complex.
Declarative
MERN STACK – Basic React applications – React Components – React State – Express REST
APIs - Modularization and Webpack - Routing with React Router – Server-side rendering • React's declarative nature means developers only describe how the UI should look, and React
handles the updates automatically. don’t need to manually manage changes to the DOM when
the view's state or data changes.
I. MERN STACK: • A React component defines how the UI should appear based on the current data. Unlike jQuery,
where you manually update the DOM when data changes, React handles the updates
The MERN stack is a popular full-stack development framework used to build modern web applications. automatically.
MERN is an acronym for MongoDB, Express.js, React, and Node.js, which together create a robust set of • React automatically calculates the differences between the old and new views, applying only the
tools for both front-end and back-end development: necessary updates. This approach ensures consistency, predictability, and makes the UI easier to
1. MongoDB: A NoSQL database used for storing data in JSON-like, flexible documents. It is maintain and understand.
designed for scalability and makes data management easier with dynamic schema. • In React, instead of refreshing the entire screen with every data change, the virtual DOM
efficiently updates only the parts that need changing. The UI is declared as a virtual
2. Express.js: A lightweight and flexible web application framework for Node.js. It simplifies representation in memory, not directly as HTML or the actual DOM.
the process of building web applications and APIs by providing essential tools for routing, • React efficiently calculates the differences between the virtual DOM and the actual DOM,
middleware, and server-side logic. applying only the necessary updates.
3. React: A powerful JavaScript library for building user interfaces, particularly single-page • This process introduces minimal overhead, as the algorithm for determining these differences is
applications (SPAs). It helps in creating reusable UI components and managing the view highly optimized for performance.
layer of the application efficiently. Component-Based
4. Node.js: A JavaScript runtime environment that allows developers to execute JavaScript Fundamental building block of React is a component, which maintains its own state and renders itself.
code outside a web browser. It enables server-side scripting, allowing the creation of scalable
and efficient back-end services. • In React, all do is build components.
• Then, put components together to make another component that depicts a complete view or page.
1 React:
• A component in React encapsulates both its data state and how it renders that data, simplifying
• React anchors the MERN stack. application development by breaking it into manageable parts.
• In some sense, it is defining component of MERN stack. • Components communicate by passing read-only properties to child components and by sending
• Facebook maintains open-source JavaScript library React, which is useful for creating HTML views. callbacks to parent components, allowing for organized data flow and interaction.
• Unlike AngularJS, React is not a framework. No Templates
It is a library. • Many web frameworks use templates to simplify the creation of repetitive HTML elements,
Thus, it does not, by itself, dictate a framework pattern such as the MVC pattern. requiring developers to learn a specific templating language.
• In contrast, React utilizes JavaScript itself to build repetitive or conditional DOM elements,
• React is primarily used to handle the "View" part in the Model-View-Controller (MVC) allowing developers to make use of their existing programming skills.
architecture, responsible for displaying the user interface. However, React doesn't enforce any
particular way to manage the rest of the application. For example, when want to construct a table, write a for(...) loop in JavaScript or use the map()
Facebook Invented React: function of an array.
• React was originally developed by Facebook engineers for internal use to address specific There is an intermediate language to represent a virtual DOM, and that is JSX, which is very similar
challenges in building user interfaces. After seeing its success, Facebook decided to make React to HTML.
available to the public by open-sourcing it, allowing developers worldwide to use and contribute to
the library. It lets create nested DOM elements in a familiar language rather than hand- constructing them using
• Before React, Facebook used a standard client-side MVC (Model-View-Controller) architecture. JavaScript functions.
In this model, the View and Model were tightly coupled, enabling two-way data binding, meaning
• JSX is a markup syntax similar to HTML used in React, but it is not a programming language. • This allows other code to run in the meantime, enhancing efficiency. It's similar to how
While it's commonly used for creating virtual DOM elements, developers can also choose to write asynchronous Ajax calls work in web development.
pure JavaScript if they prefer not to use JSX. • In Node.js, event-driven programming is a natural fit due to JavaScript features like closures.
Instead of relying on threads, Node.js handles multitasking using an event loop, which is a
Isomorphic
queue of events and their associated callbacks.
• Isomorphic JavaScript allows the same code to run on both the server and the browser, enabling • For example, when a file is ready to be read, it triggers the callback provided earlier. This event-
Server-Side Rendering (SSR). This approach improves SEO by sending pre-rendered HTML to based approach makes Node.js applications fast and eliminates the need for complex thread
the client, making it easier for search engines to index. synchronization mechanisms like semaphores and locks.
• It also allows developers to share components and logic, reducing code duplication. Overall, it • As a result, developers don't need to worry about managing concurrent tasks manually.
enhances performance and user experience by delivering faster content.
Express
Node.js
• Node.js is a runtime that runs JavaScript, but writing a web server from scratch using it can be
• Node.js is a JavaScript runtime that allows JavaScript to run outside of a browser, similar to challenging. That's where the Express framework comes in, making server development easier.
how the Java Runtime Environment (JRE) runs Java programs. • Express allows you to define routes and handle HTTP requests using flexible patterns (like
• It uses Chrome's V8 engine to execute JavaScript code independently. regular expressions).
• It simplifies parsing request data (URL, headers, parameters) and managing responses (status
Node.js Modules
codes, cookies, headers).
• In Node.js, multiple JavaScript files are managed without needing an HTML page. • Additionally, Express supports middleware—custom code that can be inserted into the
• Each file can be treated as a module, we can split the code across these modules for better request/response cycle for tasks like logging or authentication. This makes building full web
organization. applications much more efficient.
• To use code from one module in another, simply load it with the require function. This makes MongoDB
it easy to manage and reuse code across different files.
• Node.js comes with built-in core modules that are compiled into its binary. MongoDB is the database used in the MERN stack .
• These modules provide essential features like accessing the file system, handling networking, It is a NoSql document-oriented database with a flexible schema and a JSON- based query language.
managing input/output operations, and interacting with the operating system directly.
NoSQL – stands for non relational
Node.js and npm
• NoSQL databases are non-relational, meaning they don't rely on tables, columns, and strict
• NPM is the default package manager for Node.js, used to install and manage third-party libraries relationships like traditional databases do.
(packages) and their dependencies.
• They allow for horizontal scaling across multiple servers by compromising on strong consistency,
• The NPM Registry (www.npmjs.com) is a public repository where developers share their which only a few web-scale applications actually need.
modules.
• A major advantage of NoSQL is avoiding the impedance mismatch between object-oriented code
• Originally focused on Node.js modules, NPM has expanded to manage packages for browser- and relational tables, eliminating the need for ORM (Object Relational Mapping) layers.
based JavaScript, such as jQuery and React. Although React can be included directly in HTML,
• In databases like MongoDB, data is stored as objects or documents, making it easy to work with
it's recommended to install it via NPM for better management.
data in a way that matches application memory.
• Tools like Browserify or Webpack are used to bundle modules, making them browser-ready.
NPM is now the largest and fastest-growing repository, surpassing other package managers like Document-oriented:
Maven.
• It also has a unique conflict resolution technique that allows multiple conflicting versions of a • In MongoDB, a document-oriented database, data is stored as documents within collections,
module to exist side-by-side to satisfy dependencies. unlike relational databases that use rows within tables.
• Each document has a unique identifier, automatically indexed for quick access. For example,
Node.js Is Event Driven an invoice in MongoDB can be stored as a single document that includes customer details and
item lines, allowing for atomic operations on the entire invoice.
• Node.js uses an asynchronous, event-driven, non-blocking I/O model instead of relying on
• This design enables deeply nested data structures, which can be directly indexed—something
threads like other languages for multitasking. While threads create the illusion of simultaneous relational databases struggle with.
execution by switching tasks during blocked I/O operations (e.g., file reads), Node.js avoids • While MongoDB’s data is stored in a de-normalized form, leading to data duplication and
blocking entirely. increased storage use, storage costs are low today, and updates to catalog entries are infrequent.
• Instead of waiting for tasks like file opening to complete, Node.js uses callbacks to handle the • This flexibility makes MongoDB well-suited for applications that need to handle complex,
results once the task finishes. nested data without the constraints of traditional relational models.
Schema-Less Structure • Webpack can bundle and “compile” code, transforming React’s JSX syntax into pure
JavaScript for compatibility with browsers. This compilation step ensures JSX code runs
• No Fixed Schema Required: In MongoDB, objects can be stored without a pre-defined schema. smoothly in the final application.
This allows flexibility, particularly useful in the initial stages of development, as developers don’t
need to define or modify columns in advance. Isomorphic
• Dynamic Document Structure: Documents within a single collection aren’t required to share the
same set of fields. This means fields can be added to documents as needed directly through the • Single-Page Applications (SPAs) traditionally struggled with SEO because search engines
application code, avoiding database migration scripts. couldn’t fetch data through AJAX or render JavaScript.
• Caveat on Data Consistency: Although this flexibility is advantageous in early development, it • Early solutions included tools like PhantomJS or Prerender.io to generate HTML pages for SEO
shifts the responsibility for data consistency from the database to the application. For larger, more purposes.
stable applications, it’s often better to enforce some schema consistency to avoid data integrity • MERN Stack Solution: In the MERN stack (MongoDB, Express, React, Node.js), server-
issues. rendering React pages is straightforward since JavaScript can run on both the client and server.
• When React runs on the browser, it fetches data and builds the page (DOM) on the client, typical
JavaScript-Based Query Language of SPA behavior.
• To make pages SEO-friendly, React can run on the server to fetch data and render HTML, which
• JSON-Based Queries: Unlike SQL for relational databases, MongoDB uses JSON-like syntax is then sent to the client. This allows search engines to index the content more effectively.
for its query language, allowing for the creation, retrieval, updating, and deletion of documents
through JSON objects. This makes MongoDB’s queries easier to construct programmatically.
• Data Stored in BSON: MongoDB stores data in BSON (Binary JSON) format, which optimizes
space usage while keeping the data format close to JSON. When retrieving documents, they’re
returned as JSON objects, ready for immediate use in JavaScript applications.
• JavaScript Runtime Integration: MongoDB’s shell is built on a JavaScript runtime, similar to
Node.js, allowing developers to use JavaScript commands directly in the command line. Stored
procedures, equivalent to those in relational databases, can also be created using JavaScript
snippets that run on the server.
React-Router
React-Bootstrap This file will serve as the container for the React app.
• React-Bootstrap is a version of the popular CSS framework, Bootstrap, adapted for React Basic HTML Structure:
applications.
• It provides Bootstrap’s styling and functionality through React components, allowing developers • Use basic HTML tags, such as <html>, <head>, and <body>, to structure the file.
to build interfaces with pre-designed components. • The <head> section will contain the links to the required JavaScript libraries.
• Besides React-Bootstrap, other UI libraries for React include Material-UI and Elemental UI,
which also offer individual components like date pickers and tree views. Including React Libraries:
Webpack
• React is available as a JavaScript library that can be included directly in the HTML file using
the <script> tag.
• Webpack is essential for bundling and modularizing client-side code in web development.
• Other tools like Bower and Browserify serve similar purposes, but Webpack is noted for its
The React library comes in two main parts:
ease of use and lack of need for additional tools (such as Gulp or Grunt) for managing builds.
React Core: Manages React components and their state. • The virtual DOM differs from the real DOM (Document Object Model) in that it exists in the
browser’s JavaScript memory as an abstract, nested structure of React elements, rather than as actual
ReactDOM: Converts React components to a format (DOM) that browsers can understand. HTML elements.
• To render this virtual DOM on the screen, React elements must be converted to real DOM elements.
• Instead of installing React locally, you can use a Content Delivery Network (CDN) to access This is done by ReactDOM.render(), which translates each React element into corresponding
the libraries online. HTML elements through a series of document.createElement() calls.
• The ReactDOM.render() function requires two arguments: the React element to be rendered and
The URLs provided are: the target real DOM element where it should be placed, usually a <div> with a specific ID.
React: https://unpkg.com/react@16/umd/react.development.js
ReactDOM: https://unpkg.com/react-dom@16/umd/react-dom.development.js
These links should be included within <script> tags in the <head> section of the HTML file.
• Inside the <body>, add a <div> element with an id attribute (like id="content"). This <div>
will act as the container where the React elements will be rendered.
<div id=”content”><\div>
Using React.createElement():
type: Specifies the type of element, like 'div', 'span', or a custom component.
children: Any nested elements or text content. Multiple children can be passed as additional
arguments or as an array.
• The example suggests creating a <div> element with a title attribute that contains a <h1>
element with the text "Hello World!".
• This JavaScript code will go inside a <script> tag in the <body> section and will be used to
render the React element inside the container <div>.
1. Open the file in a web browser: This will load the HTML and React code.
2. Wait for React to load: It might take a few seconds for the React libraries to load fully,
especially if they are imported from a remote source.
3. Check the screen: Once loaded, you should see a caption displayed on the browser screen,
• In React, a React element—created by calling React.createElement()—is a JavaScript object as shown in Figure 5.2 (a reference image from your document).
that represents the UI to be displayed on the screen. This representation can include multiple, nested
elements that together form what is called the "virtual DOM."
4. Hover over the area: Move your mouse over the text or anywhere to its right side, within
the boundaries of an outer <div> element. When you do this, a tooltip (a small text box) with
the message "Outer div" should pop up, indicating the boundaries of that outer <div>.
JSX:
• JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. It is used
in React to define the structure of UI components in a way that’s more readable and similar to
traditional HTML.
• While it resembles HTML, JSX is not exactly the same—there are some differences in syntax.
Instead of writing complex React.createElement() calls to create an element or a hierarchy of
elements, JSX allows us to write HTML-like code that is easier to understand and manage.
• For simple elements, like a "Hello World" message, JSX looks almost identical to HTML. You
can write the element directly as you would in HTML, and assign it to a variable, effectively
replacing the need for React.createElement() calls.
• In JSX, markup isn’t enclosed within quotes, so it’s not treated as a string, and it can't be directly
used as inner HTML.
• Instead, JSX is a syntax that combines HTML-like elements with JavaScript, and this markup is
directly compiled into React.createElement() calls by React's compiler
• JSX is easy to read and understand because it resembles HTML, but browsers don’t natively
understand it.
• Therefore, JSX needs to be converted into regular JavaScript with React.createElement() calls,
which requires a compiler. Babel is the tool commonly used for this transformation.
• For production, it’s best to pre-compile JSX before sending it to the browser. However, for quick
testing or prototyping, Babel provides a standalone compiler that runs directly in the browser,
available as a JavaScript file on unpkg. Project Setup
• server-less setup for React allows you to quickly start developing without installations or
running a server. You can include React and related libraries via Content Delivery Network
(CDN) links in your HTML file.
• Using a server instead of a server-less setup improves project organization and performance,
especially for larger applications.
• To let Babel know which scripts to transform, you need to add the attribute type="text/babel" to your • In production environments, runtime compilation of JSX can slow down page loading and
script tags. Babel will look for this attribute and then transform and execute any script marked with negatively impact user experience.
it. • To address this, it's recommended to serve all files from an HTTP server and organize your
project and folder structure accordingly.
• Instructions for commands you will use in the terminal are available in a file called
commands.md located in the root of your GitHub repository.
Setting Up Node.js with nvm With npm, even an application is considered a package.
• nvm (Node Version Manager): This tool simplifies the installation and management of Package Definition and Dependencies
multiple Node.js versions. You can install Node.js directly, but using nvm is more flexible.
• Installation Instructions: • A package contains various attributes of your application, including a list of other packages
o For Mac OS or Linux, follow the instructions on nvm's GitHub page. (dependencies) that your application relies on.
o Windows users can search for "nvm for Windows" or install Node.js directly. • These dependencies may change over time as you add new libraries and features to your
• PATH Initialization: nvm modifies your shell's initialization scripts to set up the PATH application.
variable. This allows nvm to recognize the different installed versions of Node.js the next
time you open a terminal. Setting Up the Project Directory
Installing Node.js through nvm includes npm, so you don't need to install npm separately. • Example: To install Express, simply run:
Direct Installation: If you choose to install Node.js directly (without nvm), make sure to also install a npm install express
compatible version of npm to manage your packages effectively.
• Uninstalling and Installing a Specific Version:
You can confirm this by noting down the version of npm that was installed along with Node.js: o You can uninstall a package and then install a specific version like this:
Project
✓ Before we install any third-party packages with npm, it's a good idea to initialize the project.
A simple React class and instance
Components are independent and reusable bits of code. They serve the same purpose as JavaScript render() {
functions, but work in isolation and return HTML.
const continents = ['Africa', 'America', 'Asia', 'Australia', 'Europe'];
Components come in two types, Class components and Function components
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
React Class Component
const message = helloContinents.join(' ');
A class component must include the extends React.Component statement. This statement
creates an inheritance to React.Component, and gives your component access to return (
React.Component's functions.
<div title="Outer div">
The component also requires a render() method, this method returns HTML.
<h1>{message}</h1>
Example:
………………….. </div>
class Car extends React.Component {
…………… );
}
…… }
With in the class a render() method is used, which should return aa element.
Can use the sane JSX <div> with the message as the returned element. }
…
render(){ Composing Components:
return(
<div title=”example”> It is possible to build a component that uses other user defined components as well is called
<h1>{message}</h1> component composition, and it is one of the most powerful features of react.
</div>
); Example:
…..
Design main page of application as three parts:
Code for message construction within the render() function
1. A filter to select which issues to display
2. List of issues
3. An entry form for adding an issue
State Update :
If there are additional state variables (e.g., page), this.setState({ issues: newIssues })
only updates issues without affecting other state values.
To update part of the state in React, you can modify only a specific portion, rather than
replacing the entire state.
Example:
createIssue(issue) {
Async State Initialization
issue.id = this.state.issues.length + 1;
In React, while we initialize state in the constructor, real-world applications often fetch
initial data asynchronously, like from an API. In the case of an Issue Tracker, we would fetch issue.created = new Date();
the list of issues from a server. Since the constructor only allows synchronous state
initialization, we start with an empty array and then update it after the data is fetched. }
• Set issues to an empty array initially in the constructor: V.EXPRESS REST APIS
constructor() { REST (Representational State Transfer) is an architectural style used for building web services.
It defines a set of guidelines that allow a client and a server to communicate over HTTP. In a
super(); RESTful architecture:
this.state = { issues: [] }; • A client sends requests to a server to interact with resources (data or functionality), and
the server responds with the requested data or an acknowledgment of an action
} performed.
• Resources are any pieces of data or services that the server can provide, such as user
Asynchronous Data Fetching: profiles, images, or search results.
• REST APIs use standard HTTP methods (GET, POST, PUT, DELETE, etc.) to access
• After the component mounts, fetch data from the server and update the state with the or modify resources on the server.
fetched data using this.setState().
• this.setState() merges new data with existing state values without overwriting other state API Client: An API client is the component that initiates requests to the REST API. There are
variables (e.g., page). two main types of API clients:
Example of Async Fetch: 1. Development Tool: This is a tool (like Postman or Insomnia) that simplifies sending
API requests. It allows developers to test, debug, and explore APIs without needing to
• Use componentDidMount() to fetch data after the component has loaded: write code.
2. Application Service: In a software application, an API client refers to the code that
async componentDidMount() { makes requests to an API server. It uses language-specific libraries or SDKs to send
requests and handle responses. This type of client might also process the returned data API Server
and use it in the application’s logic, such as displaying information to users or
performing further operations. The API server is the component that processes incoming requests from clients. Its
responsibilities include:
API Request
• Authentication: Verifying the client's identity using credentials like API keys or
An API request is a message sent by the client to the server, asking the server to perform a tokens.
specific action or provide certain data. The structure of an API request can vary depending on • Input Validation: Ensuring the request data is correct and adheres to expected formats.
the type of API, but for REST APIs, it generally includes the following components: • Database Interaction: The API server retrieves, manipulates, or updates data stored in
the database based on the client’s request.
1. Endpoint: • Response Generation: After processing the request, the server generates and sends a
o This is the URL that specifies the resource the client wants to interact with. The response back to the client.
endpoint directs the request to the correct location on the server. For example,
in an e-commerce app, a "products" endpoint would handle requests related to Although the database itself is not directly part of the API, it stores and organizes the data that
product data (e.g., retrieving a list of products). the API server uses. The API server serves as an intermediary, facilitating communication
2. Method: between the client and the database to process and respond to requests efficiently.
o The method determines the type of operation the client wants to perform on the
resource. In REST APIs, standard HTTP methods are used: API Response
▪ GET: Retrieve data from the server.
▪ POST: Create new data on the server. Once the API server processes a request, it sends an API response to the client. This response
▪ PUT: Update existing data. typically includes:
▪ PATCH: Partially update existing data.
▪ DELETE: Remove data. • Status code: Indicating the success or failure of the request (e.g., 200 OK for success,
o For example, a GET request to the "products" endpoint would ask the server to 404 Not Found for an error).
return all the products in the database. • Response body: The actual data or result of the operation (e.g., the list of products, a
3. Parameters: confirmation message).
o These are values sent with the request to provide specific instructions or filter
the data. Parameters can be included in the URL, query string, or request body. Components of an API response:
o For example, a parameter like "color" might be used in the "products" endpoint
to return only products of a specific color (e.g., products?color=red). 1. Status Code
Request Headers The status code is an HTTP code returned by the server to indicate the outcome of the client’s
request. It helps the client understand whether the request was successful or if there was an
API request headers are key-value pairs included in the request to provide additional context issue. Some common status codes include:
or instructions for the server about the request. Some common headers include:
• 200 OK: The request was successful, and the server returned the requested data.
• Content-Type: Specifies the format of the data in the request body (e.g., • 201 Created: The request was successful, and a new resource has been created (e.g., a
application/json or application/xml). new product added to a database).
• Authorization: Provides authentication credentials to validate the requester, such as an • 404 Not Found: The server could not find the requested resource (e.g., the product does
API key or OAuth token. not exist).
These headers are essential for the server to understand the request and ensure proper handling Status codes are essential for the client to understand how to handle the response, such as
(e.g., correct data format or proper user access). whether to display the requested data or show an error message.
The request body contains the actual data that is needed to create, update, or delete a resource. Response headers provide additional information about the server's response. They are similar
For example: to request headers but are used to give context about the response. Some common response
headers include:
• If an admin wants to create a new product on an e-commerce site, the request body
might include the product’s name, brand, and price. • Cache-Control: Specifies how long the response data can be cached by the client or
• The API specification will define the required data format for the request (commonly intermediate caches (e.g., browsers or CDNs).
JSON or XML).
• Set-Cookie: Sets cookies in the client’s browser, often used for session management or // 2. Get a movie by ID
authentication purposes (e.g., saving a user’s login session).
app.get('/movies/:id', (req, res) => {
These headers guide the client in processing or storing the response. const movie = movies.find(m => m.id === parseInt(req.params.id));
3. Response Body if (!movie) return res.status(404).json({ message: "Movie not found" });
The response body contains the actual data or content returned by the server in response to the res.status(200).json(movie);
API request. It can vary depending on the type of request and the data being returned. Typically, });
the body includes:
• Structured data objects that represent the requested resources, such as a product's
// 3. Add a new movie
name, price, and description in a JSON or XML format.
• Metadata, such as the timestamp or source of the data. app.post('/movies', (req, res) => {
• Error messages or details if the request failed, explaining what went wrong (e.g., if the
requested product was not found). const { title, director, year } = req.body;
const newMovie = {
For example, a GET request for a product might return a response body containing a JSON
object with the product’s details (e.g., name, price, description), a timestamp of when the data id: movies.length + 1,
was retrieved, and information about the data source.
title,
Example:
director,
const express = require('express'); year
const app = express(); };
const port = 3000; movies.push(newMovie);
res.status(201).json(newMovie);
// Sample in-memory movie data (usually, this would come from a database) });
let movies = [
{ id: 1, title: "Inception", director: "Christopher Nolan", year: 2010 }, // 4. Update a movie
{ id: 2, title: "The Matrix", director: "The Wachowskis", year: 1999 } app.put('/movies/:id', (req, res) => {
]; const movie = movies.find(m => m.id === parseInt(req.params.id));
if (!movie) return res.status(404).json({ message: "Movie not found" });
// Middleware to parse JSON request bodies
app.use(express.json()); const { title, director, year } = req.body;
movie.title = title || movie.title;
// 1. Get all movies movie.director = director || movie.director;
app.get('/movies', (req, res) => { movie.year = year || movie.year;
res.status(200).json(movies);
}); res.status(200).json(movie);
});
VI. MODULARIZATION AND WEBPACK
// 5. Delete a movie In modularization and Webpack for front-end development, we are breaking down large codebases
into smaller, more manageable components. Let’s go through the key concepts mentioned:
app.delete('/movies/:id', (req, res) => {
Webpack for Modularization
const movieIndex = movies.findIndex(m => m.id === parseInt(req.params.id));
Webpack is a powerful tool for bundling and optimizing front-end code. It helps split the code into
if (movieIndex === -1) return res.status(404).json({ message: "Movie not found" });
smaller modules (such as components) and only loads them as needed. This improves performance by
const deletedMovie = movies.splice(movieIndex, 1); loading parts of the application incrementally rather than all at once.
res.status(204).send(); • Code Splitting: Webpack can break down the code into smaller chunks and load only what’s
necessary for the current page or feature, improving load times.
});
• Live Reloading: With the help of tools like webpack-dev-server, Webpack can refresh the
browser automatically every time you make changes to your code, making the development
// Start the server process faster and more efficient.
app.listen(port, () => { • Component-based Development: In frameworks like React, modularization allows you to
build your application using smaller, reusable components.
console.log(`Server is running on http://localhost:${port}`);
For a React app, create-react-app can serve as a boilerplate, offering a pre-configured Webpack setup
}); to get started quickly. However, this only handles the front-end (React part) of your application.
Sample REST ful API-http methods MERN Stack with Webpack
• MERN stands for MongoDB, Express, React, Node.js — a full-stack JavaScript
framework. Using mern.io can help you generate the entire directory structure for a MERN-
based application, including back-end and front-end files, and integrate Webpack for module
bundling.
Back-End Modules in Node.js
When you work with Node.js, you need to modularize the code to make it more organized and
maintainable. This is done by splitting the code into separate modules (e.g., one module for database
handling, another for authentication, etc.).
Node.js uses the CommonJS module system, where:
• require() is used to import external modules or other files.
• module.exports is used to export functions, objects, or variables from a file so they can be
used elsewhere.
In Node.js, modules are identified by either the package name (for npm packages) or the file path (for
local modules). When using require():
• For npm packages, the ID is the name of the package (which corresponds to a folder inside
node_modules).
• For local modules within the same application, the ID is the path to the file, such as ./other.js.
To use a module in another file:
1. Exporting: A module's content (function, variable, etc.) is exported using module.exports in
the module file (e.g., other.js).
2. Importing: The require() function is used to import the module, and whatever is exported is
assigned to a variable.
For example, in other.js:
module.exports = function() {
console.log("Hello from other.js");
};
And in server.js:
// server.js
const other = require('./other.js');
other(); // Outputs: Hello from other.js
Hash-based Routing: 1. Header Section: This will contain a navigation bar with hyperlinks to different views
(pages) of the application. The navigation bar will remain visible, no matter which view is
One common method for routing in SPAs is hash-based routing, which uses the URL's anchor portion displayed.
(everything after the # symbol). Here’s how it works:
2. Content Section: This section will switch between views based on the hyperlink selected in
• The part of the URL before the # remains constant (e.g., index.html), representing the single the navigation bar.
page of the SPA.
Steps:
• The hash part (#something) determines which section of the page is displayed, reflecting
different views within the application. 1. Create a Content Component:
• This method is simple, doesn’t require complex server-side configurations, and can be o This component will handle view switching based on the route selected from the
implemented easily without a routing library. navigation bar.
o Save it as Contents.jsx under the src/ui directory.
Browser History & HTML5 API:
2. Routing:
• In modern SPAs, HTML5's browser history API allows JavaScript to handle URL o Use React Router to handle routing between the views.
changes without reloading the page. This enables navigation between different views
within the application while maintaining the same page load. o The Route component from React Router is used to map a URL path to a specific
• This method is more complex than hash-based routing, as it requires handling component.
different URL requests from the server. However, it's especially useful when we want
to fully render a page from the server and ensure that search engines can crawl and o In this case, when the URL path is /issues, the Issue List view will be shown, and
index the content correctly. when the URL is /report, the Issue Report view will be shown.
Example:
Simple Routing Example:
<Route path="/issues" component={IssueList} />
In this section, you are setting up basic routing in a React application using React Router:
<Route path="/report" component={IssueReport} />
1. Two Views:
3. Redirection:
o Issue List View: This will display the list of issues you’ve been working on.
o To redirect the home page (i.e., /) to /issues, you use the Redirect component.
o Report View: A placeholder component will be created to represent the report
section. o This will automatically navigate the user to the issues page when they visit the home
page.
2. Home Page Redirection: The homepage will automatically redirect to the issue list.
<Redirect from="/" to="/issues" />
3. React Router Setup: To handle the routing, you’ll install the React Router package using
npm:
npm install react-router-dom
4. Handle No Matching Routes: <Route exact path="/report" component={IssueReport} />
o If no route matches the current URL, show a fallback message. This can be done <Route component={NotFound} /> {/* Catch-all route */}
using a default Route with no path specified or by adding a "catch-all" route.
</Switch>
In React Router, the order and configuration of routes are very important.
VII.SERVER-SIDE RENDERING (SSR)
Match Any Path:
Server-Side Rendering (SSR) is a method where the HTML of the page is generated on the server
o In React Router, you can use a route that matches any path using a catch-all route. instead of the client (browser). This approach contrasts with the typical Single-Page Application
This is helpful when you want to display a "Page Not Found" message if none of the (SPA) behavior, where the browser loads an initial HTML file and then dynamically fetches and
other routes match. renders the content via JavaScript.
o You can achieve this by defining a route without a path attribute, like this: Here’s a brief breakdown of SSR and its benefits:
const NotFound = () => <h1>Page Not Found</h1>; 1. Rendering on the Server:
<Route component={NotFound} /> o Instead of fetching the data through AJAX calls and rendering it on the client, SSR
involves the server rendering the entire HTML page before sending it to the browser.
2. Using <Switch>:
o When a user accesses a page (e.g., via a URL or refresh), the server sends a fully
o The <Switch> component ensures that only the first matching route is rendered,
rendered HTML page, which includes all the content, such as a list of issues, already
which is crucial when you have multiple routes with similar or overlapping paths.
populated.
Without <Switch>, React Router would render all routes that match the URL, not
just the first one. 2. SEO Benefits:
Example: o One of the primary advantages of SSR is that search engine crawlers can easily
index the content. Since search engines don’t typically execute JavaScript, they only
<Switch>
parse the raw HTML provided by the server.
<Route path="/issues" component={IssueList} />
o If the server sends a fully populated HTML document (not just a barebones page
<Route path="/report" component={IssueReport} /> waiting for JavaScript to populate), the search engine can index the content
effectively.
<Route component={NotFound} /> {/* Catch-all route */}
o For instance, if a page for "issues" is requested, the HTML returned by the server
</Switch> should contain the list of issues in a table, not just a placeholder waiting for JavaScript
3. Exact Matching: to load it.
o By default, React Router uses prefix matching. This means that a route like /issues 3. First-Time Page Load:
will match both /issues and /report because / is a prefix to both. o The first time a page is loaded (or when the user refreshes), the server sends the
o To avoid this and ensure that the route only matches the exact path, use the exact complete HTML.
property on the route. For example: o Once the page is loaded in the browser, subsequent navigation within the app
<Route exact path="/issues" component={IssueList} /> (without reloading) can follow the SPA model, where React handles the rendering
client-side.
4. Route Order:
4. Challenges for SPAs:
o The order of routes matters because React Router will match the first path that fits.
For example, if you have both a /issues route and a general catch-all route like /, the o SPAs excel at providing a smooth and fast user experience once the initial page is
general route might be matched first. loaded. However, for content to be indexed properly, a SPA may not be enough
because it relies on JavaScript to render the content dynamically.
o Therefore, it's important to place more specific routes (like /issues or /report) before
the general catch-all route (like * or /). o SSR solves this problem by providing the content as static HTML right away,
ensuring both fast initial load times and SEO compatibility.
<Switch>
5. Hybrid Rendering:
<Route exact path="/issues" component={IssueList} />
o In some cases, applications use Universal or Isomorphic rendering, where the o If you're using tools like Webpack or Babel, you'll need to update the configuration
application can either render on the client or the server, depending on the situation. files to correctly reference the new paths for client-side and server-side code.
o With this approach, pages can be rendered server-side for better SEO and quicker Basic Server Rendering with React
first-time load, while also allowing client-side rendering for a smooth navigation
In server-side rendering (SSR), React can generate the HTML on the server instead of the client.
experience in SPAs.
This allows the server to send pre-rendered HTML to the browser, which is beneficial for SEO and
New directory structure the initial load performance. The main difference between client-side rendering and server-side
rendering lies in the rendering process:
In the new directory structure, the goal is to better organize the project by splitting the source files
into three main directories: • Client-side rendering uses ReactDOM.render() to render a React component into the DOM.
1. src/: • Server-side rendering uses ReactDOMServer.renderToString() to generate the HTML
string on the server.
o This will store shared React components that can be used across both the client-side
(browser) and server-side code. Example: Basic About Component for SSR
o These components are common and will be used in both environments. 1. Creating the About component: You can create a simple About component which will
display some content when rendered. This component is defined as follows:
2. browser/:
// src/About.jsx
o This directory will contain files and configurations specific to the client-side
(browser). import React from "react";
o For example, the App.jsx file, which is the entry point for the client-side bundle, will export default function About() {
be placed here. This is the file that gets bundled into a single JavaScript file and
return (
served to the browser for execution.
<div className="text-center">
3. server/:
<h3>Issue Tracker version 0.9</h3>
o This directory will contain files that are specific to server-side code.
<h4>All version 1.0</h4>
o For instance, uiserver.js (which would handle server-side rendering or other server
tasks) will be moved to this directory. </div>
o These files will import the shared React components from the src/ directory to render );
content on the server side.
}
Steps for Organizing the Project:
2. Include the About component in the application: To render this About component when
1. Create the new directories: the "About" link is clicked, you need to modify your routing logic.
mkdir browser In the Contents.jsx (or wherever you define your routes), you can include the About component and
make it accessible through routing, like this:
mkdir server
// src/Contents.jsx
2. Move the relevant files into these directories:
import React from "react";
o Move App.jsx (client-side entry point) into the browser/ directory:
import { Route, Switch } from "react-router-dom";
mv src/App.jsx browser/
import About from "./About"; // Import the About component
o Move uiserver.js (server-side rendering script) into the server/ directory:
function Contents() {
mv src/uiserver.js server/
return (
3. Update the linting, compiling, and bundling configurations to reflect the new directory
structure: <div>
<Switch>
<Route path="/about" component={About} />
{/* Other routes */}
</Switch>
</div>
);
}