0% found this document useful (0 votes)
10 views28 pages

20250501111652-Module-3 Notes With Frontsheet

The document is a study material for a Full Stack Development course at SJB Institute of Technology, detailing the MERN stack, which includes MongoDB, Express.js, React.js, and Node.js. It explains the roles and features of each component, emphasizing their integration for building modern web applications. Additionally, it covers related tools and libraries that enhance development efficiency and UI design.

Uploaded by

Lavanya J
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)
10 views28 pages

20250501111652-Module-3 Notes With Frontsheet

The document is a study material for a Full Stack Development course at SJB Institute of Technology, detailing the MERN stack, which includes MongoDB, Express.js, React.js, and Node.js. It explains the roles and features of each component, emphasizing their integration for building modern web applications. Additionally, it covers related tools and libraries that enhance development efficiency and UI design.

Uploaded by

Lavanya J
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/ 28

|| Jai Sri Gurudev||

Sri Adichunchanagiri Shikshana Trust(R)

SJB INSTITUTE OF TECHNOLOGY


BGS Health & Education City, Dr. Vishnuvardhan Road, Kengeri, Bengaluru–560060
An Autonomous Institute under Visvesvaraya Technological University, Belagavi
Affiliated to Visvesvaraya Technological University, Belagavi & Approved by AICTE, New Delhi, Certified by ISO 9001-2015
Accredited by NBA & NAAC, New Delhi with ‘A+’ Grade, Recognized by UGC, New Delhi with 2(f) and 12(B)

Study Material
Course Name: Full Stack Development

Course Code: BIS601


Module – 3

By

Faculty Name: Prof. Ranjitha J


Semester: 6th ‘A’

Department of Information Science & Engineering

Aca. Year: EVEN SEM /2025


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Name of the Course: FSD (BIS601)


NOTES – Module-3

Chapter 1,2,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.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Introduction to MERN
MERN is a full-stack JavaScript solution for developing web applications, meaning both the client-side
(React) and server-side (Node.js, Express) are written in JavaScript, simplifying the development process.
The rise of MERN is linked to the trend of building Single Page Applications (SPAs), where data is
dynamically loaded without reloading the entire page. React is a key part of this as it allows for dynamic
updates to the user interface. MongoDB and Express work together to handle data and server-side logic.
The MERN stack is a popular collection of technologies used to build modern web applications.
MERN stands for:
1. MongoDB: A NoSQL database that stores data in a flexible, JSON-like format, making it ideal for
applications that require scalable and flexible data storage.
2. Express.js: A minimal and flexible Node.js web application framework that simplifies server-side
development by providing essential features like routing and middleware to handle HTTP requests.
3. React: A JavaScript library for building user interfaces. Unlike full-fledged frameworks like Angular,
React focuses on the "view" part of the MVC (Model-View-Controller) architecture. It allows developers
to create interactive and dynamic user interfaces by breaking them down into reusable components.
4. Node.js: A JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to run
JavaScript on the server-side, enabling full-stack JavaScript development (both client and server-side).

MERN Components

The MERN stack consists of four core components that work together to create modern web applications.
Here are the key components in detail:
1. MongoDB (Database)
• Type: NoSQL database.
• Role: Stores data in flexible, JSON-like documents (BSON format).
• Why MongoDB?
o It's scalable, fast, and schema-less, allowing dynamic data models.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

o Works well with JavaScript and JSON data structures.


o MongoDB is often used in situations where the data doesn't fit neatly into tables, making it perfect
for modern web apps with varied or complex data.
2. Express.js (Backend Framework)
• Type: Web application framework for Node.js.
• Role: Handles HTTP requests, routing, and middleware.
• Why Express.js?
o Simplifies the setup and creation of server-side applications.
o Manages API endpoints, sessions, cookies, authentication, and other web server-related
functionality.
o It acts as a middleware to interact with databases and the front-end efficiently.
3. React.js (Frontend Library)
• Type: Frontend JavaScript library for building user interfaces.
• Role: Renders dynamic and interactive UIs by breaking down the UI into reusable components.
• Why React?
o Component-based structure allows for modular and maintainable code.
o Virtual DOM for optimized performance and minimal UI updates.
o React is declarative, meaning you describe what the UI should look like, and React takes care of
updates when data changes.
o It’s commonly used to build Single Page Applications (SPAs).
4. Node.js (JavaScript Runtime)
• Type: JavaScript runtime environment.
• Role: Runs JavaScript code server-side, enabling you to use JavaScript for both front-end and back-end
code.
• Why Node.js?
o Asynchronous, non-blocking, and event-driven, making it well-suited for real-time applications
and high-performance tasks.
o Runs JavaScript code outside the browser, which helps unify development for both front-end and
back-end teams. The npm package manager makes it easy to integrate third-party libraries.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

React Component

1. React is the "V" (View) in MVC:


o Unlike AngularJS, which is a full framework, React is a library that focuses on rendering views.
o You can integrate React into any architecture rather than being forced into an MVC pattern.
2. Why Facebook Created React:
o Initially, Facebook used a traditional client-side MVC model, but it became too complex.
o React was created to handle state changes declaratively, avoiding messy cascading updates that
made the UI hard to maintain.
3. Declarative UI & Virtual DOM:
o Traditional jQuery Approach: Manually update the DOM when data changes.
o React Approach: Define how the UI should look based on the current state. React then figures out
the minimal updates using the Virtual DOM.
o The Virtual DOM is an in-memory representation of the real DOM, which helps improve
performance by minimizing direct DOM manipulations.
4. Component-Based Architecture:
o React applications are made of components, each with its own state and logic.
o Components can be nested to form complex UI structures.
o Data is passed through props (read-only) and callbacks (for communication between components).
5. No Templates – Uses JavaScript Instead:
o Many frameworks rely on templating languages (like Angular’s templates).
o React uses JavaScript and JSX (JavaScript XML), making it easier for developers who already
know JavaScript.
6. Isomorphic (Universal) Nature:
o React can run both on the browser and the server.
o Server-side rendering (SSR) in React (with Node.js) helps with SEO and initial page load speed.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

MongoDB

MongoDB is a NoSQL database used in the MERN stack (MongoDB, Express.js, React.js, Node.js). It
stores data as documents (JSON-like objects) instead of using tables and rows like relational databases
(MySQL, PostgreSQL).

• A NoSQL document-oriented database that stores data in JSON-like BSON (Binary JSON)
format.
• Unlike SQL databases, MongoDB doesn’t enforce a fixed schema, making it flexible for storing
different types of data.
• Supports horizontal scaling and replication, meaning it can distribute data across multiple servers
for better performance.
1. NoSQL Database
• NoSQL = Non-Relational → No tables, rows, or foreign keys

• Two key features:


Horizontal Scalability – Data can be distributed across multiple servers
No ORM Required – Directly store objects instead of mapping them to tables
MongoDB queries use JSON-based syntax, making it easier to work with JavaScript applications.

2. Document-Oriented Storage
• Instead of tables and rows, MongoDB uses collections and documents.

• Each document = a JSON-like object (stored as BSON for efficiency).


SQL vs. MongoDB for storing an invoice:

Feature SQL (Relational DB) MongoDB (NoSQL)


Structured as tables with rows and Uses JSON-like flexible documents (BSON
1. Data Model
columns format)
2. Schema Requires a predefined schema with
Schema-less; fields can vary across documents
Flexibility strict structure
Uses foreign keys and joins to link Embeds related data within documents (nested
3. Relationships
tables objects)
Scales vertically (adding more Scales horizontally (distributed across multiple
4. Scalability
resources to one server) servers)
Can be slower due to joins and
5. Performance Faster reads and writes with denormalized data
normalization
Fully ACID-compliant for multi-row Supports multi-document transactions but
6. Transactions
transactions favors eventual consistency
Uses SQL (Structured Query
7. Query Language Uses MongoDB Query Language (MQL)
Language)
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Feature SQL (Relational DB) MongoDB (NoSQL)


Uses B-tree and hash indexes for Supports multiple indexing strategies (e.g.,
8. Indexing
faster lookups compound, text, geospatial)
Enforces strict data validation More flexible but requires manual validation
9. Data Integrity
through constraints logic
10. Use Case for Best when invoices need structured Best for flexible invoice models with embedded
Invoices relational integrity items, taxes, etc.

3. Schema-Less Database
• No predefined schema → You can add fields dynamically.
• Great for rapid development (no need for migrations).
4. JavaScript-Based Query Language
• Unlike SQL (which uses SELECT, WHERE, etc.), MongoDB queries are written in JSON-like
syntax.
• Built-in support for JavaScript → Works well with Node.js.

5. BSON (Binary JSON) Format


• MongoDB stores data in BSON, a binary-encoded JSON format.

• Why BSON?
More efficient storage
Supports additional data types (e.g., date, binary)
Faster querying

6. Scalability and Performance


• MongoDB can distribute data across multiple servers (sharding).

• Relational databases ensure strong consistency (always up-to-date data), but MongoDB prioritizes
availability and partition tolerance (CAP theorem).
• Trade-off: MongoDB allows eventual consistency (data may not be instantly updated everywhere).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Nodejs

• Node.js is JavaScript outside the browser – It allows JavaScript to run independently as a


runtime environment (similar to how Java runs on the Java Runtime Environment).
• It is built on Chrome’s V8 JavaScript engine, making it fast and efficient.
Who uses Node.js?
o Many large companies, including Netflix, Uber, and LinkedIn, use Node.js for its
scalability and performance.
1. Node.js Modules and CommonJS
• Unlike browser JavaScript, where HTML pages load JavaScript files, Node.js does not rely on
HTML.
• Node.js uses modules (libraries) to organize code better.
• CommonJS Module System:
o You load modules using require(), which is not available in browser JavaScript.
o There are three types of modules:
1. Core Modules – Built into Node.js (e.g., fs, http, path).
2. Third-Party Modules – Installed using npm.
3. User-Defined Modules – Created by developers for better code organization.

2. npm – The Node.js Package Manager


• npm (Node Package Manager) is the default package manager for Node.js.

• It allows easy installation and management of third-party libraries.


• npm registry (www.npmjs.com) has millions of packages (e.g., Express.js, React).
• Tools like Webpack and Browserify help bundle JavaScript modules for browsers.

3. Event-Driven, Non-Blocking Architecture


• Most languages use threads for multi-tasking – When waiting for an operation (e.g., reading a
file), the thread blocks (stops execution) until it's done.
• Node.js uses an event-driven model – Instead of blocking, it uses callbacks and the event loop to
handle multiple tasks asynchronously.
4. How Node.js Handles Asynchronous Tasks:
• A task (e.g., reading a file) is started.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• Instead of waiting, Node.js moves to the next task.


• When the file is ready, an event triggers a callback function.
• This makes Node.js faster and more efficient than traditional blocking I/O.

5. Why Choose Node.js?

Fast Execution – Uses V8 engine for high-speed JavaScript execution.


Non-Blocking I/O – Handles multiple tasks efficiently.
Modular Architecture – Uses a clean module system (CommonJS).
Massive Ecosystem – npm provides millions of reusable packages.
Scalability – Well-suited for real-time applications like chat apps, streaming services, and microservices.

Expressjs

Express.js is a framework for Node.js that makes it easy to build web servers and APIs. Node.js alone is just
a runtime environment; writing a server from scratch in Node.js is complex. Express simplifies web server
development by handling routing, middleware, and HTTP request/response management.
1. Easy to set up – Requires minimal code to create a server.
2. Powerful routing system – Handles different HTTP methods (GET, POST, etc.).
3. Supports middleware – Allows modular and reusable code.
4. Works well with APIs – Ideal for RESTful services and Single Page Applications (SPAs).
5. Scalable – Used in production by companies like Uber, PayPal, and Twitter.

Express vs. Node.js Without Express

Feature Node.js (without Express) Express.js


Routing Manual parsing of URLs Built-in routing system
Request Handling Complex HTTP handling Simple functions (app.get(), app.post(), etc.)
Middleware Manually implemented Built-in support (app.use())
Static Files Needs fs module express.static()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Other Tools & Library

1. React-Router (Client-Side Routing)


• Problem: React only handles rendering components; it does not manage navigation (URLs).

• Solution: React-Router enables client-side routing, meaning users can navigate between pages
without full-page reloads.
• How It Works:
o Similar to Express.js routing but for the frontend.
o Updates the URL and loads the correct React component without refreshing the page.
o Manages the browser’s Back button functionality.
2. React-Bootstrap (UI Framework for React)
• Problem: Styling and UI components are time-consuming to build from scratch.

• Solution: React-Bootstrap provides pre-built responsive UI components (buttons, modals, forms,


etc.).
• Alternative UI Libraries:
o Material-UI (MUI) – Google's Material Design for React.
o Ant Design – Feature-rich UI framework.
3. Webpack (Module Bundler)
• Problem: JavaScript files can become large and unmanageable.

• Solution: Webpack bundles multiple files into a single optimized file for the browser.
• Key Features:
o Converts JSX, ES6+ code into browser-friendly JavaScript.
o Supports CSS, images, fonts processing.
o Allows lazy loading for better performance.
4. ESLint (Code Linter for JavaScript/React)
• Ensures consistent coding style and catches errors early.

ESLint is a widely used static code analysis tool (linter) for JavaScript and React applications. It helps
developers identify and fix code errors, enforce coding standards, and improve overall code quality. By
analyzing JavaScript and JSX code, ESLint detects issues such as syntax errors, undefined variables,
unused imports, and inconsistent formatting.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

5. Bootstrap
Bootstrap is a popular CSS framework that helps developers create responsive and visually appealing
websites quickly. It provides a collection of pre-designed components such as buttons, forms, modals, and
navigation bars, which can be easily customized. Bootstrap also includes a responsive grid system that uses
Flexbox and CSS Grid to ensure layouts adjust properly on different screen sizes. Additionally, it comes
with built-in JavaScript components like carousels and tooltips. It is widely used for front-end development
to simplify UI design without writing extensive custom CSS.
6. Babel
Babel is a JavaScript compiler that allows developers to write modern JavaScript (ES6 and beyond) while
ensuring compatibility with older browsers. Since not all browsers support the latest JavaScript features,
Babel converts newer syntax—such as arrow functions, async/await, and classes—into older ES5
JavaScript that can run everywhere. It is commonly used in conjunction with tools like Webpack and React,
where JSX and modern JavaScript features are frequently used. By using Babel, developers can write
cleaner, future-proof code without worrying about browser limitations.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Server-less Hello World


The Server-less Hello World is a simple example of how to use React and ReactDOM in a single HTML
file to render a "Hello World!" message, all without the need for a server or complex setup.
Here’s the process:
1. HTML Structure:
You begin with a basic HTML file that includes the essential tags like <html>, <head>, and <body>.
2. Including React Libraries:
In the <head> section, you include React and ReactDOM using <script> tags pointing to CDN URLs:
o React: Manages the creation and handling of components and their states.
o ReactDOM: Converts React components into actual DOM elements that can be rendered in the
browser.
3. Creating the React Element:
o Inside the <body>, you create a div element with an id="content", which will later hold your React
components.
o Using React.createElement(), you define a React element. In this case, a div with a title attribute
containing an h1 heading with the text "Hello World!".
4. Rendering the Element:
o Finally, you use ReactDOM.render() to render the React element inside the div with the ID
content in the HTML page.
5. Result:
When opened in a modern browser, this file will display the message "Hello World!" inside a div
element, and you can hover over the div to see the tooltip showing its title.
Listing 2-1. index.html: Server-less Hello World
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

You can test this file by opening it in a browser. It may take a few seconds to load the React libraries, but
soon enough, you should see the browser displaying the caption, as seen in Figure 2-1. You should also be
able to hover over the text or anywhere to its right side within the boundaries of the outer div, and you
should be able to see the tooltip “Outer div” pop up.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

JSX (JavaScript XML)


JSX is a syntax extension for JavaScript that allows developers to write UI components in a way that
closely resembles HTML. It simplifies writing React components and improves code readability.
Why JSX?
In traditional React, elements are created using React.createElement(), which can become cumbersome
when creating deeply nested structures. JSX simplifies this process by providing a more readable and
HTML-like syntax.
Example: Without JSX
const element = React.createElement(
'div',
{ title: 'Outer div' },
React.createElement('h1', null, 'Hello World!')
);
Example: With JSX
const element = (
<div title="Outer div">
<h1>Hello World!</h1>
</div>
);
JSX makes the code cleaner and easier to understand.
Key Points About JSX
1. Not HTML – JSX looks like HTML but is actually JavaScript with XML-like syntax.
2. Not a String – JSX is not treated as a string but as JavaScript expressions.
3. Needs Compilation – Browsers do not understand JSX directly. It is transformed into
React.createElement() calls using Babel, a JavaScript compiler.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Babel and JSX


Since browsers do not support JSX, Babel is used to compile JSX into JavaScript. To enable JSX in a
browser for prototyping, the Babel standalone compiler can be included:
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
Scripts containing JSX must be marked with type="text/babel" so that Babel knows to transform them:
<script type="text/babel">
const element = (
<div title="Outer div">
<h1>Hello World!</h1>
</div>
);
ReactDOM.render(element, document.getElementById('contents'));
</script>
Performance Considerations
• Runtime Compilation: Using Babel in the browser slows down execution since JSX is compiled at
runtime.
• Build-Time Compilation: A better approach is to compile JSX during the build process using tools
like Webpack and Babel.

Project Set-Up
This section explains how to properly set up a React project for development and production, moving beyond the
simple server-less approach used for initial learning.
Why Move Beyond Server-Less Setup?
1. Performance Issues in Development
o Using CDNs to load scripts introduces additional time.
o Babel compiler, which converts JSX to JavaScript, is large and can slow down loading times.
2. Performance Issues in Production
o Runtime compilation of JSX (done in the browser) affects page load speed.
o For large-scale applications, this reduces user experience.
Solution:
Setting up a proper project with Node.js and an HTTP server.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Step 1:
Installing nvm (Node Version Manager)
Windows: Use nvm-windows or install Node.js directly. After installing nvm, restart your shell/terminal.
Step 2:
Installing Node.js using nvm
nvm install 10(long term support)
Check the node version - node --version
Check the npm version - npm --version
Step 3:
Setting Up a React Project
1. Create a new project folder:
mkdir pro-mern-stack-2
cd pro-mern-stack-2
2. Initialize a new npm project: npm init
Step 4:
Installing Express (HTTP Server) - Install Express framework to serve React files:
npm install express

Express
Express is a lightweight framework for building web servers in Node.js.Initially, the focus is on serving
static files (like index.html) to understand how Express works without deep server-side coding.
This explanation provides an introduction to Express.js, a web framework for Node.js. It walks through
setting up an Express server to serve static files and explains important concepts related to Express.
1. Installing Express
• Express needs to be installed using:

npm install express@4


• Running this command multiple times is safe; it won’t reinstall if it's already installed.
2. Importing Express
• In Node.js, modules are imported using require():

const express = require('express');


• This imports Express into the script.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

3. Creating an Express Application


• Express provides a function to create a web application instance:

const app = express();


• This app represents the Express application (our web server).

4. Serving Static Files


• Static files (HTML, CSS, JS, images, etc.) are usually stored in a public directory.

• Express has built-in middleware (express.static) to serve these files:


const fileServerMiddleware = express.static('public');
app.use('/', fileServerMiddleware);
• Alternatively, it can be written more concisely:

app.use(express.static('public'));
• This middleware:

o Looks for files inside the public/ directory.


o Serves them when requested (e.g., http://localhost:3000/index.html).
5. Starting the Server
• The Express app needs to listen on a port (e.g., 3000):

app.listen(3000, function () {
console.log('App started on port 3000');
});
• Running the server:

node server.js
• This will start a web server, accessible at http://localhost:3000/.

6. Using npm start Instead of node server.js


• Instead of manually running node server.js, we can define a start script in package.json:

"scripts": {
"start": "node server/server.js"
}
• Now, just running:

npm start
will start the server.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Separate Script Files in JSX Development


In previous examples, JSX (JavaScript XML) was transformed at runtime in the browser. This is inefficient because
every time the page loads, the JSX is compiled into JavaScript on the fly, which slows down performance.
To optimize this, we should move the transformation to the build stage before deploying the app. The first step is to
separate JSX and JavaScript code into a separate script file instead of keeping it inside index.html.

Since we moved JSX out of index.html, we need to create a new file App.jsx inside the public directory:
App.jsx
const element = (
<div title="Outer div">
<h1>Hello World!</h1>
</div>
);
ReactDOM.render(element, document.getElementById('contents'));
• This contains only the JSX code, without the <script> tag.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

JSX Transform
JSX (JavaScript XML) is a syntax extension used in React that allows us to write HTML-like code inside
JavaScript files. However, browsers do not understand JSX natively. This is where Babel comes in—it
transforms JSX into standard JavaScript that browsers can execute.

Steps for JSX Transformation:


1. Organizing JSX Files
o A new directory (src/) is created to store all JSX files.
o App.jsx is moved into src/, ensuring a structured project layout.
2. Installing Babel for JSX Transformation
Babel is required to convert JSX to standard JavaScript. We install the necessary Babel tools:
npm install --save-dev @babel/core@7 @babel/cli@7
o @babel/core: The core Babel library.

o @babel/cli: The command-line interface to run Babel commands.


3. Checking Babel Installation
Since Babel is installed locally (not globally), it must be accessed via its path:
node_modules/.bin/babel --version
Alternatively, npx (available in npm v6+) allows running it without specifying the full path:
npx babel --version
4. Installing JSX Preset for Babel
Babel requires a preset to understand JSX syntax:
npm install --save-dev @babel/preset-react@7
o @babel/preset-react: A plugin that helps Babel transform JSX into JavaScript.

5. Compiling JSX to JavaScript


The command below converts JSX files inside src/ to plain JavaScript and places the output in the
public/ directory:
npx babel src --presets @babel/react --out-dir public
o src: The directory containing JSX files.

o --presets @babel/react: Applies the JSX transform.


o --out-dir public: Saves the output JavaScript files in the public/ directory.
The transformed file (App.js) will now contain React.createElement() calls instead of JSX.

Updating index.html
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

After the transformation:


• The reference to App.jsx in index.html needs to be updated to App.js.

• The Babel runtime script (used for on-the-fly JSX transformation in the browser) is no longer
needed.
Changes in index.html
Before:
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script src="/App.jsx" type="text/babel"></script>
After:
<script src="/App.js"></script>
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Issue Tracker

Issue Tracker
These applications help you create a bunch of issues or bugs, assign them to people, and track their statuses.
These are essentially CRUD applications (Create, Read, Update, and Delete a record in a database) that
manage a list of objects or entities. The CRUD pattern is so useful because pretty much all enterprise
applications are built around the CRUD pattern on different entities or objects. In the case of the Issue
Tracker, we’ll only deal with a single object or record, because that’s good enough to depict the pattern.
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 Class
React class component is a javascript class that extends React.Component,which is the base class provided
by the react library. It must include a render() method. This method tells react what to display on the screen
and must return a react element(e.g., a JSX element like <div>).
React Classes are a way to create reusable and powerful UI components.
Before React Hooks (introduced in React 16.8), class components were the standard way to:
• Manage state

• Handle lifecycle events (e.g., when the component is mounted, updated, etc.)
• Respond to user interactions
Now, both Class Components and Function Components can be used, but this chapter focuses on the
traditional Class Component style.

A React Class Component is built by extending React.Component. It must have at least a render() method.

• HelloWorld is a class.
• It extends React.Component, which means it inherits everything React needs to render it.
• The render() function tells React what UI to show on the screen.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• Array.from() is used to create an array of greetings: ["Hello Africa!", "Hello America!", ...]
• join(' ') merges them into a single string
• JSX is returned with that message inside an <h1>

Term Meaning
HelloWorld The component class you defined
<HelloWorld /> An instance of that component (like using <div> in HTML)
div, h1 Built-in React components
render() The method React calls to show UI
React.Component The base class every custom class must extend
Element The object representation of <HelloWorld /> passed to ReactDOM
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Composing Component
• Larger components should be split into fine-grained components when there is a logical separation
possible between the fine-grained components. In this section we’ll create logically separated 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. For example, a
specialization of an existing component can be done by passing properties to the generic component rather
than inheriting from it.
• In general, remember to keep coupling between components to a minimum (coupling is where one
component needs to know about the details of another component, including parameters or properties
passed between them).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Passing a Data using Props


In React, components can receive data from their parent components through a special object called props. This
makes components reusable and dynamic, enabling you to pass different data into the same component structure.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

This structure shows that:


• IssueList is the top-level container component.

• It contains three child components:


o IssueFilter: for filtering issues.
o IssueTable: displays a table of issues.
o IssueAdd: a form to add a new issue.
IssueTable contains multiple IssueRow components, each representing one issue.
Instead of hardcoding each issue into the component, you pass data like issue_id, issue_title, and rowStyle
as props to the IssueRow:
<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" />
Each of these props is accessed in the child component (IssueRow) like so:
<td style={this.props.rowStyle}>{this.props.issue_id}</td>
<td style={this.props.rowStyle}>{this.props.issue_title}</td>
This makes IssueRow reusable and capable of displaying different data depending on what is passed to it.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Passing a Data using Children


Normally, in React, we pass data using props like this:
<IssueRow issue_id={1} issue_title="Some issue" />
But in some cases, instead of passing the data as an attribute, we can pass it as nested content (children)
inside the component tags:
<IssueRow issue_id={1}>
Error in console when clicking Add
</IssueRow>
In this case, the text "Error in console when clicking Add" is child content, and can be accessed inside the
IssueRow component as this.props.children.

Dynamic Composition
Instead of manually writing multiple <IssueRow> components, React allows us to dynamically generate
these rows from a JavaScript array. This is useful when:
• You have a list of items (like issues).

• You want to loop through them and render components for each item.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

The browser displays a full issue tracker table, dynamically generated from the array — with columns for all issue
fields, formatted neatly and flexibly styled via CSS.

Prepared By,
Prof. Ranjitha J,
Dept, of ISE
SJB Institute of Technology

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