0% found this document useful (0 votes)
10 views

NOTES(AWT)

Uploaded by

ravindra MO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

NOTES(AWT)

Uploaded by

ravindra MO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

SRINIVAS UNIVERSITY

INSTITUTE OF ENGINEERING AND


TECHNOLOGY
MUKKA, MANGALURU

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

NOTES

ADVANCED WEB TECHNOLOGY


SUBJECT CODE: 23SCS061

COMPILED BY:
Ms. Madhura Rao K, Assistant Professor

2024-2025
MODULE 1
PHP and MySQL
What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language used
primarily for web development. It can also be used for general-purpose
programming.
Features of PHP
1. Platform Independent:
o PHP code runs on multiple platforms (Windows, macOS,
Linux) and integrates seamlessly with all major web servers
(Apache, Nginx, IIS).
2. Open Source:
o PHP is free to use, which makes it accessible for developers
and companies alike.
3. Embedded in HTML:
o PHP code can be embedded directly into HTML for
dynamic content generation.
4. Supports Object-Oriented Programming (OOP):
o PHP offers OOP features like classes, inheritance,
interfaces, traits, and namespaces.
5. Error Handling:
o Error reporting and exceptions: PHP supports much errors
reporting constants to generate errors and relevant warnings
at run time. For example E_ERROR, E_WARNING,
E_PARSE, E_STRICT. PHP5 supports exception handling
which is used to throw errors which can be caught at any
time.
6. Loosely typed language:

ADVANCED WEB TECHNOLOGY(23SCS061) Page 1


o PHP encourages the use of variables without declaring its
data types. So this is taken care at the execution time
depending on the value assigned to the variable. Even the
variable name can be changed dynamically.
7. Regular expression:
o PHP provides regular expression functions with parsing and
pattern matching methods.
8. Cross-platform compatibility:
o PHP is multi-platform and known for its portability as it can
run on any operating System and windows environments.
The most common are XAMPP (Windows, Apache Server,
MySQL, Perl, and PHP) and LAMP (Linux, Apache,
MySQL, PHP).
Basic syntax of PHP
o A PHP script starts with <?php and ends with ?>.
Syntax:
<?php
// PHP code goes here
?>
Example:
<?php
echo "Hello, This is PHP script";
?>

Variables in PHP
o Declared using a dollar sign ($) followed by the variable
name.
o echo is used to print the PHP statements to the output
screen.
Example:
<?php
$name = "John"; // variable assigned with value

ADVANCED WEB TECHNOLOGY(23SCS061) Page 2


echo "Hello, $name!"; // print statement with variable
to print its value
?>
Data Types
PHP supports various data types:
➢ String: "Hello"
➢ Integer: 42
➢ Float: 3.14
➢ Boolean: true or false
➢ Array: ["apple", "banana"]
➢ Object, NULL, and Resource

Control Structures and Loops in PHP


Control structures are constructs in programming languages that dictate
the flow of execution of a program based on conditions, iterations, or
sequences. They allow you to control how statements are executed,
making your code more dynamic and functional.
o Simple if
o if else
o else if ladder
o switch
o while
o do-while
o for
o foreach
Examples :
<?php
// Example of if-else statement
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}

ADVANCED WEB TECHNOLOGY(23SCS061) Page 3


// Example of if-elseif-else statement
$grade = 85;
if ($grade >= 90) {
echo "Excellent!";
} elseif ($grade >= 75) {
echo "Good job!";
} else {
echo "You need to work harder.";
}

// Example of switch statement


$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week.";
break;
case "Friday":
echo "Almost the weekend!";
break;
case "Sunday":
echo "Relax, it's the weekend.";
break;
default:
echo "Just another day.";
break;
}
?>

// while loop
<?php
$count = 1;
while ($count <= 5) {
echo "Count is: $count<br>";
$count++;
ADVANCED WEB TECHNOLOGY(23SCS061) Page 4
}
?>

//do while
<?php
$count = 1;
do {
echo "Count is: $count<br>";
$count++;
} while ($count <= 5);
?>

// for loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i<br
}
?>
// foreach loop
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit<br>";
}
?>
Functions in PHP
A function in PHP is a reusable block of code that performs a specific
task. Functions help in organizing code, making it modular, and
avoiding repetition. Functions can accept input (parameters) and
optionally return a value.

Syntax:
function functionName($parameter1, $parameter2)

ADVANCED WEB TECHNOLOGY(23SCS061) Page 5


{
// Code to execute
return $result; // Optional
}

Example:
<?php
// Function definition
function greet($name) {
return "Hello, $name!";
}
// Function call
echo greet("John"); // Output: Hello, John!
?>
Arrays in PHP
An array in PHP is a data structure that can store multiple values in a
single variable. Arrays can hold a collection of values, which can be
indexed numerically or associatively.

Types of Arrays:
Indexed Array: Uses numeric keys (default).
Associative Array: Uses named keys.
Multidimensional Array: An array containing other arrays.

Example:

<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple

// Associative array
$person = ["name" => "John", "age" => 25];
ADVANCED WEB TECHNOLOGY(23SCS061) Page 6
echo $person["name"]; // Output: John

// Multidimensional array
$students = [
["name" => "Alice", "grade" => 85],
["name" => "Bob", "grade" => 90]
];
echo $students[1]["name"]; // Output: Bob
?>

HTML Forms in PHP

HTML forms are used to collect user input, and PHP is commonly used
to handle and process the form data on the server side. An HTML form
allows users to input data through various fields, such as text boxes,
checkboxes, radio buttons, and submit buttons.

Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form Example</title>
</head>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<input type="submit" value="Submit">
</form>
ADVANCED WEB TECHNOLOGY(23SCS061) Page 7
</body>
</html>

Form handling in PHP


PHP handles form data sent via GET or POST methods. The data can
be accessed using the superglobals $_GET or $_POST.
$_GET:
• Used to collect form data sent via the GET method.
• Also used to retrieve query parameters from the URL.
Example:
<?php
if (isset($_GET['name'])) {
echo "Hello, " . htmlspecialchars($_GET['name']);
}
?>
// Access via URL: example.com?name=John
$_POST:
• Used to collect form data sent via the POST method.
Example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
echo "Hello, $name";
}
?>

Processing form data with PHP

ADVANCED WEB TECHNOLOGY(23SCS061) Page 8


Form processing refers to the act of collecting, handling, and
managing data submitted through an HTML form. It involves retrieving
the user input, validating it, performing operations based on the input
(e.g., saving to a database, sending an email, or displaying a response),
and returning feedback to the user.
Steps in Form Processing
1. Design the HTML Form:
o Create an interface for users to input data, such as text
fields, checkboxes, or file uploads.
2. Submit the Form:
o Users submit the form using the GET or POST HTTP
methods, which sends the input to the server.
3. Retrieve the Data:
o The server-side script (e.g., in PHP) collects the data using

predefined variables like $_POST or $_GET.


4. Validate the Input:
o Ensure the data is valid (e.g., checking required fields, email
format, or specific criteria).
5. Sanitize the Data:
o Clean the input to prevent malicious code injection (e.g.,
XSS or SQL Injection).
6. Process the Data:
o Perform actions such as storing data in a database, sending
emails, or calculating results.
7. Provide Feedback:
o Inform the user whether the submission was successful, or
display error messages for invalid input.
Example:

<!---HTML form-->
<!DOCTYPE html>
<html>
<head>

ADVANCED WEB TECHNOLOGY(23SCS061) Page 9


<title>Form Processing Example</title>
</head>
<body>
<h1>Login Form</h1>
<form action="process.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"
required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

<!----- process.php----->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and retrieve data
$username = htmlspecialchars(trim($_POST["username"]));
$password = htmlspecialchars(trim($_POST["password"]));

// Validate input
if (empty($username) || empty($password)) {
echo "Both fields are required.";
} else {
// Simulate processing (e.g., database check)
if ($username == "admin" && $password == "1234") {
echo "Welcome, $username!";
} else {
echo "Invalid username or password.";
ADVANCED WEB TECHNOLOGY(23SCS061) Page 10
}
}
} else {
echo "Invalid form submission.";
}
?>

File Uploads and Handling


PHP makes it easy to upload and handle files through HTML
forms. File uploading involves transferring a file from the client
(browser) to the server, and handling includes saving, renaming, or
processing the uploaded file.
Example:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Select a file:</label>
<input type="file" name="file" id="file" required>
<br><br>
<input type="submit" value="Upload">
</form>
</body>
</html>

upload.php
ADVANCED WEB TECHNOLOGY(23SCS061) Page 11
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Access the uploaded file details
$file = $_FILES["file"];

// File properties
$fileName = $file["name"];
$fileTmpName = $file["tmp_name"];
$fileSize = $file["size"];
$fileError = $file["error"];
$fileType = $file["type"];

// Define allowed file types


$allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

// Validate file
if ($fileError === 0) {
if (in_array($fileType, $allowedTypes)) {
if ($fileSize <= 2 * 1024 * 1024) { // 2 MB limit
// Move the file to the upload directory
$uploadDir = "uploads/";
$uploadPath = $uploadDir . basename($fileName);

if (move_uploaded_file($fileTmpName, $uploadPath)) {
echo "File uploaded successfully!<br>";
echo "File Name: $fileName<br>";
echo "File Type: $fileType<br>";
echo "File Size: " . ($fileSize / 1024) . " KB<br>";
} else {
echo "Error moving the uploaded file.";
}
} else {
echo "File size exceeds the 2 MB limit.";
ADVANCED WEB TECHNOLOGY(23SCS061) Page 12
}
} else {
echo "Invalid file type. Only JPG, PNG, and PDF files are
allowed.";
}
} else {
echo "Error uploading file. Error code: $fileError";
}
}
?>

Working with cookies and sessions

Cookies: A cookie is a small piece of data that the server sends to the
client (browser) to store on the user's device. Cookies are used to
remember user preferences, login details, and other information.
Sessions: A session is a way to store information to be used across
multiple pages. When a user visits a website and starts a new session,
the server creates a unique session ID and stores it in a cookie on the
user’s computer. The server also creates a file on the server to store the
session variables for that user.

Example:
Start a session and cookie
<?php
// Start the session
session_start();

// Set session variable


$_SESSION["username"] = "JohnDoe";

// Set cookie for 1 day


setcookie("user_logged_in", "true", time() + 86400, "/");
ADVANCED WEB TECHNOLOGY(23SCS061) Page 13
echo "Session and cookie have been set!";
?>

Retrieve the session and cookie

<?php
// Start the session
session_start();

// Check if session variable exists


if (isset($_SESSION["username"])) {
echo "Welcome " . $_SESSION["username"] . "<br>";
} else {
echo "No session data found.<br>";
}

// Check if cookie exists


if (isset($_COOKIE["user_logged_in"]) &&
$_COOKIE["user_logged_in"] == "true") {
echo "You are logged in via cookie!";
} else {
echo "Cookie not found.";
}
?>

Destroying the cookies and sessions

<?php
// Start the session
session_start();

// Unset session variable


ADVANCED WEB TECHNOLOGY(23SCS061) Page 14
unset($_SESSION["username"]);

// Destroy the session


session_destroy();

// Delete the cookie by setting its expiration time in the past


setcookie("user_logged_in", "", time() - 3600, "/");

echo "Session and cookie have been destroyed!";


?>

MySQL database

MySQL is an open-source Relational Database Management System


(RDBMS) that uses Structured Query Language (SQL) to manage and
manipulate data stored in relational databases. It is one of the most
popular databases used in web development and is widely used in
combination with server-side scripting languages like PHP.
Key Concepts in MySQL
1. Database: A database is a collection of data stored in a structured
format, usually consisting of tables. Each database can have
multiple tables.
2. Table: A table in MySQL is where data is stored in rows and
columns. It is similar to a spreadsheet, where each column
represents a different field, and each row represents a record.
3. Row (Record): A row in a table represents a single, complete
record in the database. For example, one row could represent a
user, and each column in that row could represent a user's
attributes (name, email, etc.).

ADVANCED WEB TECHNOLOGY(23SCS061) Page 15


4. Column (Field): A column represents a particular data type (like
text, number, date, etc.) for each record in the table. For example,
in a "Users" table, the columns could be id, username, email, and
password.
5. SQL (Structured Query Language): MySQL uses SQL to
interact with the database. SQL is a standard language for
managing and manipulating relational databases. Examples of
SQL commands include SELECT, INSERT, UPDATE, and
DELETE.
Creating database and tables
✓ Creating a Database: CREATE DATABASE my_database;
✓ Listing of Databases: show databases;
✓ Selecting a Database: USE my_database;
✓ Creating a Table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100),
email VARCHAR(100),
password VARCHAR(255)
);
✓ Inserting Data into a Table:
INSERT INTO users (username, email, password)
VALUES ('john', '[email protected]', 'password123');
✓ Selecting Data:
SELECT * FROM users;

✓ Updating Data:

ADVANCED WEB TECHNOLOGY(23SCS061) Page 16


UPDATE users SET password = 'newpassword' WHERE
username = 'john';

✓ Deleting Data:
DELETE FROM users WHERE username = 'john';

✓ Dropping a Table:
DROP TABLE users;

Connecting MySQL with PHP


Connecting MySQL with PHP involves establishing a communication
channel between a PHP application and a MySQL database to enable
data exchange, such as storing, retrieving, updating, and deleting
records.
Steps to Connect MySQL with PHP
1. Install Prerequisites
Ensure you have installed the following on your system:
• MySQL: The database management system.
• PHP: The server-side scripting language.
• A web server like Apache or Nginx.
You can use tools like XAMPP, WAMP, or MAMP, which include all
these components.
2. Create a Database and Table in MySQL
Access MySQL via phpMyAdmin, MySQL Workbench, or the
command line.
Create a database
3. Create a table within the database

ADVANCED WEB TECHNOLOGY(23SCS061) Page 17


4. Write a PHP Script to Connect to MySQL
<?php
$servername = "localhost";
$username = "root";
$password = ""; // provide your password here
$dbname = "my_database"; // provide the database name that you have
created

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Executing SQL queries with PHP


To execute SQL queries in PHP, you use either the MySQLi or PDO
extension. These queries can perform operations like inserting,
retrieving, updating, and deleting records in a database.
Steps to Execute SQL Queries:
1. Establish a Connection
Before executing any SQL queries, connect to the database. Use either
MySQLi or PDO.
2. Execute SQL Queries
you can execute different types of queries using both MySQLi and
PDO.
ADVANCED WEB TECHNOLOGY(23SCS061) Page 18
Using MySQLi to execute queries:
//inserting a data
<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query
$sql = "INSERT INTO users (username, password) VALUES ('john',
'secure_password')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close connection
$conn->close();
?>

//Retrieving a data
<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");

// Check connection
ADVANCED WEB TECHNOLOGY(23SCS061) Page 19
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query
$sql = "SELECT id, username FROM users";
$result = $conn->query($sql);

// Display results
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Username: " . $row["username"] .
"<br>";
}
} else {
echo "No records found";
}

// Close connection
$conn->close();
?>

//Updating a data

<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

ADVANCED WEB TECHNOLOGY(23SCS061) Page 20


// SQL query
$sql = "UPDATE users SET password='new_password' WHERE
username='john_doe'";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

// Close connection
$conn->close();
?>

// Deleting a data

<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query
$sql = "DELETE FROM users WHERE username='john_doe'";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
ADVANCED WEB TECHNOLOGY(23SCS061) Page 21
echo "Error deleting record: " . $conn->error;
}

// Close connection
$conn->close();
?>

Handling Database Transaction

Handling database transactions effectively is crucial to ensure data


consistency and integrity, especially in multi-user or multi-threaded
environments. The transaction has four properties. These are used to
maintain consistency in a database, before and after the transaction.
ACID Properties:
• Atomicity: The transaction is all or nothing.
• Consistency: The database remains in a valid state before and
after the transaction.
• Isolation: Transactions do not interfere with each other.
• Durability: Once committed, the changes persist even in case of

a crash.

Steps to Handle Transactions

• Begin Transaction
Start a transaction before executing operations.
For example: BEGIN TRANSACTION;
conn = db.connect() // When MySQL integrated with PHP
conn.begin()
• Perform Operations
Execute the SQL queries (INSERT, UPDATE, DELETE, etc.)
within the transaction.
• Commit the Transaction

ADVANCED WEB TECHNOLOGY(23SCS061) Page 22


Once all operations are successfully executed, commit the
transaction to save changes.
conn.commit() // In PHP MySQL integration code
• Rollback on Failure
If an error occurs, rollback the transaction to revert changes.
ROLLBACK;
conn.rollback() // In PHP MySQL integration code
• Close Connection
Always close the database connection after completing the
transaction.
conn.close()

CODE SNIPPET

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Start transaction
$conn->begin_transaction();

try {
// Execute queries

ADVANCED WEB TECHNOLOGY(23SCS061) Page 23


$conn->query("INSERT INTO users (name, age) VALUES
('Alice', 25)");
$conn->query("UPDATE accounts SET balance = balance
- 100 WHERE user_id = 1");

// Commit transaction
$conn->commit();
echo "Transaction committed successfully.";
} catch (Exception $e) {
// Rollback on error
$conn->rollback();
echo "Transaction failed: " . $e->getMessage();
} finally {
// Close connection
$conn->close();
}
?>

Transaction States in DBMS

ADVANCED WEB TECHNOLOGY(23SCS061) Page 24


MODULE 2
JAVA SCRIPT FRAMEWORKS
Introduction to Javascript
A JavaScript framework is a pre-written collection of JavaScript code
that provides developers with a structure for building web applications
more efficiently. Frameworks simplify repetitive tasks, enforce best
practices, and often offer tools for managing the complexities of
modern web development, such as UI updates, state management, and
routing.
Overview of Javascript framework
JavaScript frameworks are powerful tools that provide developers with
pre-defined structures and utilities to create modern web applications.
They streamline development by offering reusable components,
libraries, and methods for common tasks like managing data, routing,
and updating user interfaces dynamically.
Popular JavaScript Frameworks
1. React (Library, but often considered a framework)
• Developer: Meta (formerly Facebook)
• Features:
o Component-based architecture
o Virtual DOM for high performance
o Extensive ecosystem (Redux, Next.js, etc.)
• Use Cases: Dynamic web applications, single-page applications
(SPAs)
2. Angular
• Developer: Google
ADVANCED WEB TECHNOLOGY(23SCS061) Page 25
• Features:
o Two-way data binding
o Dependency injection
o Built-in tools for testing
• Use Cases: Enterprise-grade applications, large-scale apps
3. Vue.js
• Developer: Evan You
• Features:
o Lightweight and flexible
o Reactive data binding
o Progressive adoption (use as much or as little as needed)
• Use Cases: Small to medium-sized apps, interactive UIs
4. Svelte
• Developer: Rich Harris
• Features:
o No virtual DOM
o Compiles components at build time
o Lightweight and fast
• Use Cases: High-performance, lightweight applications
5. Next.js (React-based framework)
• Developer: Vercel
• Features:

ADVANCED WEB TECHNOLOGY(23SCS061) Page 26


o Server-side rendering (SSR)
o Static site generation (SSG)
o API routes
• Use Cases: SEO-friendly web apps, JAMstack apps
6. Node.js (Runtime environment, often used with frameworks)
• Developer: Open-source, supported by the Node.js Foundation
• Features:
o Server-side JavaScript execution
o Non-blocking, event-driven architecture
o Large package ecosystem via npm
• Use Cases: Backend services, real-time apps
Core Features of JavaScript Frameworks
1. Component-based Architecture: Build reusable and self-
contained UI components.
2. Data Binding: Sync data between the UI and application state
seamlessly.
3. State Management: Handle the application's data flow and state
changes effectively.
4. Routing: Manage navigation between different views or pages in
SPAs.
5. Performance Optimization: Frameworks often include features
like virtual DOM or compilation to enhance performance.

Pros and Cons of Using JavaScript Frameworks

ADVANCED WEB TECHNOLOGY(23SCS061) Page 27


JavaScript frameworks can significantly accelerate development and
improve the quality of web applications. However, they also come
with some drawbacks.
Pros(Advantages):
• Efficiency and Productivity: Provides pre-built tools and
reusable components for faster development.
• Maintainability and Scalability: Enforces structured code and
modular design for easy scaling.
• Performance Enhancements: Optimizes rendering and state
management for better performance.
• Cross-Browser Compatibility: Ensures uniform behavior across
different browsers.
• Community and Ecosystem: Offers extensive community
support, plugins, and libraries.
• Future-Proofing: Regular updates keep frameworks aligned
with modern standards.
Cons(Disadvantages):
• Learning Curve: Requires time to learn and adapt to framework-
specific concepts.
• Framework Lock-in: Makes switching frameworks or deviating
from their conventions difficult.
• Overhead: Adds abstraction layers and larger bundle sizes,
which may not suit small projects.
• Frequent Updates: Regular updates may introduce breaking
changes and require maintenance.
• Dependency Risks: Relies on third-party tools that may have
vulnerabilities or become obsolete.

React.js Fundamentals
ADVANCED WEB TECHNOLOGY(23SCS061) Page 28
React.js is a popular JavaScript library for building user interfaces,
particularly for single-page applications (SPAs). It allows developers
to create reusable UI components and manage application state
efficiently.
Key Concepts:
1. Components
• Definition: Reusable, self-contained pieces of UI.
• Types:
o Functional Components: Simple functions returning JSX.
o Class Components: ES6 classes with additional features like
state and lifecycle methods.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
2. JSX (JavaScript XML)
• Definition: A syntax extension that looks like HTML and allows
embedding HTML in JavaScript.
• Example:
const element = <h1>Hello, World!</h1>;
3. Props (Properties)
• Definition: Read-only data passed from a parent to a child
component.
• Example
function Greeting(props) {

ADVANCED WEB TECHNOLOGY(23SCS061) Page 29


return <h1>Hello, {props.name}!</h1>;
}
4. State
• Definition: Mutable data managed within a component to track
changes.
• Example (Functional Component with Hooks)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count+1)}>Increment</button>
</div>
);
}
5. Lifecycle Methods
• Definition: Methods in class components triggered at different

stages of a component's life (e.g., mounting, updating,


unmounting).
• Example (Class Component)

class Clock extends React.Component {


componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

ADVANCED WEB TECHNOLOGY(23SCS061) Page 30


render() {
return <h1>{new Date().toLocaleTimeString()}</h1>;
}
}
6. Hooks
• Definition: Functions that allow functional components to use

state and lifecycle methods.


• Common Hooks:

o useState: For managing state.

o useEffect: For handling side effects (e.g., API calls,

subscriptions).
Example:
import { useEffect, useState } from "react";
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(timer); // Cleanup
}, []);
return <h1>{time.toLocaleTimeString()}</h1>;
}
7. Virtual DOM
• Definition: A lightweight copy of the DOM used to optimize

updates by minimizing direct DOM manipulations.


8. Event Handling
• Definition: React uses camelCase syntax for events and functions

to handle interactions.
• Example:

function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
ADVANCED WEB TECHNOLOGY(23SCS061) Page 31
}
9. Conditional Rendering
• Definition: Render different UI elements based on conditions.

• Example:

function Greeting(props) {
return props.isLoggedIn ? <h1>Welcome Back!</h1> :
<h1>Please Sign In</h1>;
}
10. Routing (React Router)
• Definition: Manage navigation between views or pages in a React

app.
• Example:

import { BrowserRouter, Route, Link } from "react-router-dom";


function App() {
return (
<BrowserRouter>
<nav>
<Link to="/home">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}
What are Components in React?
Components are independent and reusable blocks of code which work
in isolation. The main advantage of components is that they help reduce
redundancy.

How to create a functional component in React


function Greet() {
return <h1>Hello World!</h1>;
ADVANCED WEB TECHNOLOGY(23SCS061) Page 32
}
OR
const Greet = () => <h1>Hello World!</h1>

How to nest components in React


In React, we can nest components inside one another. This helps in
creating more complex User Interfaces. It also helps in getting rid of
redundant code. The components that are nested inside parent
components are called child components.

const Book = () => {


return (
<div>
<h1>Book name : Cracking The Coding Interview</h1>
<h2>Author : Gayle Laakmann McDowell</h2>
</div>
);
};
Here, a Book component is created. If we want to create more such
instances of the book component we can use nested components.

const BookList = () => {


return (
<div>
<Book />
<Book />
</div>
);
};

const Book = () => {


return (
<div>
ADVANCED WEB TECHNOLOGY(23SCS061) Page 33
<h1>Book name : Cracking The Coding Interview</h1>
<h2>Author : Gayle Laakmann McDowell</h2>
</div>
);
};
In the above code block, we have created two components, Book and
BookList. Book returns a div that has Book name and author
name while BookList returns a div that contains two books.
In this way, nesting helps us create multiple instances of a component
to create complex User Interfaces easily.

What is JSX?
• JSX stands for JavaScript XML. It's an extension of the JavaScript
language based on ES6. It's translated into regular JavaScript at
runtime.
• JSX allows us to write HTML in React which makes the process
of writing HTML in your React apps much easier.

// Plain HTML
const myElement = React.createElement('h1', { style:{color:"green"}
}, 'I do not use JSX!');
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

// JSX
const myElement = <h1>I have used JSX!</h1>;
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

ADVANCED WEB TECHNOLOGY(23SCS061) Page 34


JSX Rules:
1. A React component name must be capitalized. Component names
that do not begin with a capital letter are treated like built-in
components.
2. JSX allows you to return only one element from a given
component. This is known as a parent element.
How Props Work in React
• Props stand for properties. Props are like function arguments, and
you send them into the component as attributes.
• When we want to create multiple instances of a single component
with various different values, we need to use props.
const Book = (props) => {
return (
<div>
<h1>Book name : {props.bookName}</h1>
<h2>Author : {props.author}</h2>
</div>
);
};
but there's another way of accessing props. That is accessing each and
every element of an object.
const Book = (props) => {
const {bookName, author} = props;
return (
<div>
<h1>Book name : {bookName}</h1>
<h2>Author : {author}</h2>
</div>
);
};
ADVANCED WEB TECHNOLOGY(23SCS061) Page 35
const Book = ({bookName, author}) => {
return (
<div>
<h1>Book name : {bookName}</h1>
<h2>Author : {author}</h2>
</div>
);
};
It works just the same as the previous method but we just destructure
the content of the props in the parameter section instead of doing it by
declarations.

Children props
Sometimes, we might come across situations in which we need to add
a specific element to a particular instance of a component only. In those
cases, we use children props.
const BookList = () => {
return (
<div>
<Book bookName = "Cracking The Coding Interview"
author = "Gayle Laakmann McDowell">
<button> Read Now! <button/>
< Book />
<Book bookName = "The Road to Learn React"
author = "Robert Wieruch"/>
</div>
);
};

ADVANCED WEB TECHNOLOGY(23SCS061) Page 36


In the above code block, we want to display a button only for the first
book instance. That's why we used a child component by passing the
button between opening and closing tags.

Key Props
A key is a special attribute you need to include when creating lists of
elements in React. We use keys to give an identity to elements in lists.
We need to specify an id or any unique value to each instance of a
component to keep track of their addition or removal.
const App = () => {
const numbers = [1, 2, 3, 4, 5];
return (
<>
{numbers.map((number, index) => {
return <li key={index}> {number} </li>;
})}
</>
);
};

States in React
• React components has a built-in state object.
• The state object is where you store property values that belong to
the component.
• When the state object changes, the component re-renders.

Example:
// Specify the state object in the constructor method
class Car extends React.Component {
constructor(props) {
super(props);
ADVANCED WEB TECHNOLOGY(23SCS061) Page 37
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}

// The state object can contain as many properties as you like


class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}

Using the state Object

ADVANCED WEB TECHNOLOGY(23SCS061) Page 38


Referring to the state object anywhere in the component by using
the this.state.propertyname

// Refer to the state object in the render() method


class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}

Changing the state Object


To change a value in the state object, use the this.setState() method.

// Add a button with an onClick event that will change the color
property
ADVANCED WEB TECHNOLOGY(23SCS061) Page 39
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
}
}

ADVANCED WEB TECHNOLOGY(23SCS061) Page 40


ADVANCED WEB TECHNOLOGY(23SCS061) Page 41
ADVANCED WEB TECHNOLOGY(23SCS061) Page 42

You might also like